簡體   English   中英

動態 canDeactivate Guard:在離開帶有更改的表單之前顯示確認消息

[英]Dynamic canDeactivate Guard: Show confirm message before navigating away from form with changes

我正在處理一個包含大量表單頁面的項目,我想在最終用戶嘗試導航到另一條路線而不保存更改時向他們提供提示。 在所有頁面中,我都使用類似這樣的反應形式

this.mainForm = this.formBuilder.group(...

那么我可以讓我的所有組件都停用Guard 嗎?

@Injectable()
class CanDeactivateTeam implements CanDeactivate<... something magic here want to pass component dynamically...> {

constructor() {}

canDeactivate(
    component: ...dynamicComponent,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState: RouterStateSnapshot
    ): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree {
        if(!this.mainForm.dirty) return true;
    }
}

是否可以對所有頁面使用相同的可以停用保護以防止表單更改?

提前致謝。

您將需要表單基礎組件。 基礎組件將具有檢查表單是否臟並返回解析為布爾值的承諾的功能。

在您的 CanDeactivateGuard 中,您可以調用此函數。 現在您只需要從這個基本組件繼承所有表單組件並更新路由集 canDeactivate。

//CanDeactivateGuard.ts

export class CanDeactivateGuard implements CanDeactivate<AdminFormBaseComponent> {
     canDeactivate(component: FormBaseComponent): Observable<boolean> | boolean 
     {
        return component.verifyChangesAndConfirm();
     }
}


//FormBaseComponent.ts
export class FormBaseComponent{
   @ViewChild('form', { static: true }) form;

   public verifyChangesAndConfirm(): Observable<boolean> | boolean {
      if (this.form && !this.form.submitted && this.form.dirty) {
         var subject = new Subject<boolean>();
         this._modalService.ShowConfirmDialog(() => {
            //yes
            subject.next(true);
         }, () => {
            //no
            subject.next(false);
         });
         return subject.asObservable();
     }
     return true;
   }
}

//SomeDataEntryFormComponent.ts
export class SomeDataEntryFormComponent extends FormBaseComponent implements 
OnInit {
   //Other code
}

並且在路由配置中應該有以下條目

{ path: 'some-data-entry-form', component: SomeDataEntryFormComponent, canDeactivate: 
[CanDeactivateGuard] },

您將必須實現模態服務並注入,以便 _modalService.ShowConfirmDialog 工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM