Lifecycle hooks as observable

One of trait of lifecycle in components and directives is that, you can not observe it. If you must do something within one of this lifecycle, you have to declare variable first and then assign value in hook. This can cause some problems, but there is a very simple solution. Check how you can omit this in a very easy way.

July 17, 2022 angular

Observable lifecycle hooks

In Angular, you can use RxJS to observe lifecycle hooks. To observe lifecycle hooks you can use push next event ReplaySubject when a new value arrived.

@Component({
  /*...*/
})
export class TabsComponent implements AfterContentInit {
  @ContentChildren(TabComponent) tabsSelector: QueryList<TabComponent>;

  private contentInit$ = new ReplaySubject<void>(1);
  tabs$ = this.contentInit$.pipe(
    map(() => this.tabsSelector.toArray()),
    switchMap((tabs) => this.tabsSelector.changes.pipe(startWith(tabs))),
  );

  ngAfterContentInit() {
    this.contentInit$.next();
    this.contentInit$.complete();
  }
}

Do you like the content?

Your support helps me continue my work. Please consider making a donation.

Donations are accepted through PayPal or Stripe. You do not need a account to donate. All major credit cards are accepted.

Leave a comment