简体   繁体   中英

What is the best way to destroy a component instance in angular?

I have an Angular app and it have a button to switch between two components. I found an issue when i'm playing with the button a bit and sometimes a component is inheriting some behavior from the other component, so I'm looking for a way to start a fresh and clean instance each time i'm switching. I tried to do some unsubscribe in the ngOnDestroy() but it won't help much!

Disclaimer : I do not prefer writing code that handles creating and destroying components manually. Rather one should rely on framework's routing, child-parent hierarchy and *ngIf to create and destroy components. You should of course deal with your code during creation and destruction using ngOnInit and ngOnDestroy .

However, I assume you are using ComponentFactoryResolver.resolveComponentFactory for manually initialising and destroying component.

If that is the case, you can use :

viewContainerRef.clear();

where viewContainerRef is your component placeholder. This ensures that no information from previous component is held within the viewContainerRef while loading new instances.

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