[英]How to destroy a child component inside a parent component
我正在使用Angular 2 +
父组件
searchResultComponent
该组件显示产品列表作为搜索结果。
模板.html:
<div [routerLink]="['product/'+item.id]" ></div>
<!--When user click this DOM, the child component(ProductDetailComponent) will be loaded and navigated.. -->
<router-outlet></router-outlet>
子组件
ProductDetailComponent
我想要做的是当用户单击div时,如果加载了现有的子组件,则现有的子组件将被销毁,并且可以重新创建新的子组件。
角度问题:路由器仅在导航到其他路线时销毁并重新创建组件。 如果仅更新路由参数或查询参数,但路由相同,则不会销毁并重新创建组件。 要解决此问题,这是解决方案。 相同页面时,“路由器导航”不会调用ngOnInit 。 但是解决方案不能完全解决问题,几乎没有错误。
activeRouter.params.subscribe(val=>{
//move the code from ngOnInit to here
})
我的问题是,当用户单击父组件中的按钮时,如何在重新加载子组件之前完全破坏子组件?
到目前为止,我在父组件中尝试过的操作如下,但始终会出现类型错误:this.component未定义。 因为子组件仅在路线更改时加载。
component:ComponentRef;
CheckingChildCom(){
if(this.component){ this.component.destroy(); }
}
经过研究,我发现解决问题的最佳方法是
下标即可观察路线参数的变化,而无需破坏ProductDetailComponent。
private activeRouter: ActivatedRoute,
ngOnInit() {
this.activeRouter.paramMap.subscribe(param =>{
//put codes here
});
}
在组件上使用ngIf
<component-selector *ngIf="someCondition"></component-selector>
想要销毁时将someCondition设置为false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.