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.

Portrait of the author

About me

A JavaScript specialist with many years of industry experience whose heart beats for Angular. A follower of the "Keep it simple, stupid" principle and a fan of clean code and good architecture. Fearless in the face of the toughest challenges, I always look for simple and effective solutions. As a pragmatist and an enthusiast of new technologies, I passionately follow the trends in the JavaScript world. After hours — a sailor who loves discovering new places and spending time on trips. My favorite motto? "Talk is cheap. Show me the code."

Leave a comment