Search code examples
angulartypescriptabstract-class

Angular - find out if derived class implements an abstract class (router.component)


I'm trying to use router.component to set page title. So, I created an abstract class which has to provide title:

export abstract class ComponentWithTitleBase {
  abstract get title(): Observable<string>;
}

and then the component that implements it looks like this:

export class AboutComponent extends ComponentWithTitleBase implements OnInit {
  get title(): Observable<string> {
    return of("About the demo");
  }

  ngOnInit(): void {}
}

Now I just need to use it with router events. I subscribe and see if router.component is ComponentWithTitleBase, so:

    this.router.events
      .pipe(
        // identify navigation end
        filter((event) => event instanceof NavigationEnd),
        // now query the activated route
        map(() => this.rootRoute(this.route)),
        filter((route) => !!route.component),
        tap((route: ActivatedRoute) =>
          console.log(route.component instanceof ComponentWithTitleBase)
        ),
...

But whatever I do the output is false. Is there any way I could find out if some class implements another abstract class?


Solution

  • instanceof does not work for an abstract class,

    Replace route.component instanceof ComponentWithTitleBase with ComponentWithTitleBase.isPrototypeOf(route.component)