Search code examples
angularcastingtypescript-genericsangular-guards

How to get a generic component property that has been passed into my canDeactivate Guard in Angular?


I want to pass multiple components (Component1 | Component2) into my canDeactivate guard, so I'm using generics like this below.

Problem - There is a property I want to access from each of the components I pass in, so how do get the generic components property?

Do I have to cast or something? I can see in the debugger that the component is there, but I can't access the properties until I'm inside the function live.

FYI - component.profileForm.dirty doesn't work because it doesn't know what T is until I'm inside the function

export class PreventUnsavedChangesGuard <T> implements CanDeactivate <T> {

  constructor(private confirmService: ConfirmService) {}

  canDeactivate(component: T): Observable < boolean > | boolean {
    if (component.hasOwnProperty('profileForm')) {
      if (component.profileForm.dirty) {
        return this.confirmService.confirm();
      }
    }
    return true;
  }

}


Solution

  • You could define an interface containing the minimal information you expect your component to have, e.g.,

    interface HasProfileForm {
        profileForm: Form
    }
    

    and then you could modify your guard to be use the new interface, e.g.,

    export class PreventUnsavedChangesGuard <T extends HasProfileForm> implements CanDeactivate <T> {
    
      constructor(private confirmService: ConfirmService) {}
    
      canDeactivate(component: T): Observable<boolean> | boolean {
        if (component.hasOwnProperty('profileForm')) {
          if (component.profileForm.dirty) {
            return this.confirmService.confirm();
          }
        }
        return true;
      }
    }