0

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

}
chuckd
  • 13,460
  • 29
  • 152
  • 331

1 Answers1

1

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;
  }
}
Jacopo Lanzoni
  • 1,264
  • 2
  • 11
  • 25
  • Hi Jacopo. I figured out I get the property by doing this: if (component['profileForm'].dirty), would your solution be better or worse than what I did? – chuckd Nov 22 '20 at 08:21
  • I think it would be better because you would enforce that requirement through a type, which somehow the big thing behind Typescript. – Jacopo Lanzoni Nov 22 '20 at 08:31