1

I'm working on a project with lot of forms pages, I want to give intimation to the end-user whenever they try to navigate to another route without saving their changes. In all the pages I'm using reactive forms something like this

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

So can I have one can deactivate Guard for all my components something like this

@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;
    }
}

is it possible to have the same can deactivate guard for all the pages to prevent form changes?

Thanks in advance.

Hemant
  • 338
  • 4
  • 11
Arjun
  • 547
  • 2
  • 6
  • 23

1 Answers1

1

You will need form base component. Base component will have function to check if form is dirty and return a promise which resolves to boolean.

In your CanDeactivateGuard you can call this function. Now you just need inherit all form components from this base component and update routes set 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
}

And there should be following entry in route configuration

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

You will have to implement modal service and inject so that _modalService.ShowConfirmDialog works.

Hemant
  • 338
  • 4
  • 11