簡體   English   中英

如何銷毀父組件中的子組件

[英]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

})

如何在angular2中再次調用ngOnInit()

我的問題是,當用戶單擊父組件中的按鈕時,如何在重新加載子組件之前完全破壞子組件?

  • 到目前為止,我在父組件中嘗試過的操作如下,但始終會出現類型錯誤: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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM