Description
I ran into this problem and I'll try to explain it here.
With nativescript-angular
the lifecycle hook ngOnDestroy
isn't called when we navigate away from a page as it would be on web. Navigating back reuses the old component with nativescript-angular
but a new instance is created on web.
I've based an example on Nathan Walker's angular2-seed-advanced
:
https://github.com/m-abs/angular2-seed-advanced/tree/ngondestroy-not-triggered
I've two component for my routes:
HomeComponent
AboutComponent
Each component have a instanceNo
, so we can identify multiple instances of the component.
Action | Web | TNS |
---|---|---|
Launch application | HomeComponent<1>.ngOnInit() is called | HomeComponent<1>.ngOnInit() is called |
Click on 'ABOUT' | HomeComponent<1>.ngOnDestroy() followed by AboutComponent<1>.ngOnInit() | AboutComponent<1>.ngOnInit() |
Click on 'HOME' | AboutComponent<1>.ngOnDestroy() followed by HomeComponent<2>.ngOnInit() | HomeComponent<2>.ngOnInit() |
Click back | HomeComponent<2>.ngOnDestroy() followed by AboutComponent<2>.ngOnInit() | HomeComponent<2>.ngOnDestroy() |
Click back again | AboutComponent<2>.ngOnDestroy() followed by HomeComponent<3>.ngOnInit() | AboutComponent<1>.ngOnDestroy() |
As you can see the two behaves very differently.
On web:
- Navigate to a new page, the current component is destroyed and a new is created.
- Navigating hitting back, the current component is destroyed and a new is created.
With nativescript-angular:
- Navigate to a new page, creates the new component but leaves the current component as is.
- Navigating hitting back, the current component is destroyed and the old component is reused.
If you want to try for yourself, checkout my branch ngondestroy-not-triggered
and run:
For web:
npm run start
For nativescript-angular with android:
npm run start.livesync.android
Shouldn't the two behave the same?
So components are destroyed when we navigate from a page and (re)created when we navigate to the page?