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

On a daily basis, I work as a Front-End Developer with a primary focus on JavaScript. I feel most comfortable with Angular and NestJS, but I’m always eager to venture beyond a single tech stack. I effectively leverage AI tools in my workflow, which allows me to quickly onboard into new technologies and write code in other languages or frameworks whenever needed.

After hours, I bring my passion for tech into the physical world. I run my own homelab, where I experiment with server management and build home automation and monitoring powered by Home Assistant.

Leave a comment