Angular use modal dialog in canDeactivate Guard service for unsubmitted changes (Form dirty)

前端 未结 7 2524
北荒
北荒 2020-12-05 19:35

In my Angular 4 application I have some components with a form, like this:

export class MyComponent implements OnInit, FormComponent {

  form: FormGroup;

          


        
7条回答
  •  执笔经年
    2020-12-05 20:00

    This is my implementation to get a confirmation dialog before leaving a certain route using ngx-bootstrap dialog box. I am having a global variable called 'canNavigate' with the help of a service. This variable will hold a Boolean value if it is true or false to see if navigation is possible. This value is initially true but if I do a change in my component I will make it false therefore 'canNavigate' will be false. If it is false I will open the dialog box and if the user discards the changes it will go to the desired route by taking the queryParams as well, else it will not route.

    @Injectable()
    export class AddItemsAuthenticate implements CanDeactivate {
    
      bsModalRef: BsModalRef;
      constructor(private router: Router,
                  private dataHelper: DataHelperService,
                  private modalService: BsModalService) {
      }
    
      canDeactivate(component: AddUniformItemComponent,
                    route: ActivatedRouteSnapshot,
                    state: RouterStateSnapshot,
                    nextState?: RouterStateSnapshot): boolean {
        if (this.dataHelper.canNavigate === false ) {
          this.bsModalRef = this.modalService.show(ConfirmDialogComponent);
          this.bsModalRef.content.title = 'Discard Changes';
          this.bsModalRef.content.description = `You have unsaved changes. Do you want to leave this page and discard
                                                your changes or stay on this page?`;
    
          this.modalService.onHidden.subscribe(
            result => {
              try {
                if (this.bsModalRef && this.bsModalRef.content.confirmation) {
                  this.dataHelper.canNavigate = true;
                  this.dataHelper.reset();;
                  const queryParams = nextState.root.queryParams;
                  this.router.navigate([nextState.url.split('?')[0]],
                    {
                      queryParams
                    });
                }
              }catch (exception) {
                // console.log(exception);
              }
            }, error => console.log(error));
        }
    
        return this.dataHelper.canNavigate;
    
      }
    }
    

提交回复
热议问题