简体   繁体   中英

Is Angular ComponentA destroyed when navigating away to ComponentB?

Suppose ComponentA is displayed in the <RouterOutlet> and the user navigates such that ComponentB is displayed in the same <RouterOutlet >. Is the ComponentA instance then destroyed such that a new instance of ComponentA is created if the user navigates back to ComponentA again?

If ComponentA implements OnInit this would result in ComponentA.onInit() being called twice.

yes, you are right. if any component is loaded by angular route inside 'RouterOutlet' then when another component gets loaded, the current component gets destroyed after calling it's last callback method ngOnDestroy().

If componentA is replaced by another component, the ngOnDestroy() method of componentA is called. But the stuff created by componentA is not destroyed automatically. If you want to clean up stuff created by componentA, you have to do it yourself by writing code inside ngOnDestroy() method of componentA.

For example, if you have subscribed some endless observables in ngOnInit() , you need to unsubscribe it in ngOnDestroy() , otherwise the subscription will be active even after another component has replaced componentA.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM