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.

1
@Component({
2
/*...*/
3
})
4
export class TabsComponent implements AfterContentInit {
5
@ContentChildren(TabComponent) tabsSelector: QueryList<TabComponent>;
6
7
private contentInit$ = new ReplaySubject<void>(1);
8
tabs$ = this.contentInit$.pipe(
9
map(() => this.tabsSelector.toArray()),
10
switchMap((tabs) => this.tabsSelector.changes.pipe(startWith(tabs))),
11
);
12
13
ngAfterContentInit() {
14
this.contentInit$.next();
15
this.contentInit$.complete();
16
}
17
}

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