Can ngOnDestroy happen before ngAfterContentInit?

380 views Asked by At

Suppose a component has two lifecycle hooks:

{
    ngAfterContentInit() {
        this.subscription = rx.Observable
        .interval()
        .subscribe(value => this.value = value)
    },
    ngOnDestroy() {
        this.subscription.unsubscribe()
    }
}

Is it possible for ngOnDestroy to be called before ngAfterContentInit, and, if so, why exactly? This seems to be the case during fast enough component insertion/removal in my application. Docs are not clear about the subject.

I'm asking this question to know if ngOnDestroy should not assume that anything from other lifecycle callbacks is defined and bulletproof ngOnDestroy should perform presence checks, like this:

ngOnDestroy() {
    this.subscription && this.subscription.unsubscribe()
}
1

There are 1 answers

1
Estus Flask On BEST ANSWER

The documentation is very clear on the order of lifecycle hooks and doesn't consider the possibility of changing the order.

Moreover, as it can be seen in this example, component compilation process is synchronous. If there are templates to load, they are requested prior to compilation.

The initialization should result in this log:

bootstrap
bootstrap tick
constructor
ngOnInit
ngAfterContentInit
ngAfterViewInit
constructor tick

For synchronous operations there's no opportunity for some piece of code to be 'faster' and run out of order.

this.subscription && ... check is not needed.