0

I am using Angular 2 +

parent component

searchResultComponent

This component shows a list of products as the search result.

template .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>

Child Component

ProductDetailComponent

What I want to do is when the user click the div, if there is a existing child component loaded, the existing child component will be destroyed and a new child component can be recreated.

Angular Issue: The router only destroys and recreates the component when it navigates to a different route. When only route params or query params are updated but the route is the same, the component won't be destroyed and recreated. To fix it, this is the solution. Router Navigate does not call ngOnInit when same page. But the solution is not fully fix the problem, there are few bugs.

activeRouter.params.subscribe(val=>{
   //move the code from ngOnInit to here

})

How to call ngOnInit() again in angular2

My question is how to destroy a child component completely before reloading the child component when user click the button in the parent component ?

  • What I have tried so far in the parent component is as below, but always get type error: this.component is undefined. Because the child component only load when the route changes.

    component: ComponentRef;

    checkingChildCom(){

       if(this.component){
           this.component.destroy();
       }
    

    }

Kevin
  • 272
  • 5
  • 21
  • try this: https://angular.io/guide/dynamic-component-loader – Pal Singh Oct 11 '18 at 03:52
  • @Pal Singh Thanks for the suggestion. But our app route logic is hard to change. The child component is loaded when the route changed and matched with path: 'product/:id', and then the child component will be loaded. – Kevin Oct 11 '18 at 05:09

2 Answers2

0

After doing research, I found the best way to solve the problem is to

subscript to watch the route para changes and don't need to destroy the ProductDetailComponent.

private activeRouter: ActivatedRoute,
ngOnInit() {
  this.activeRouter.paramMap.subscribe(param =>{
    //put codes here
  });
}
Kevin
  • 272
  • 5
  • 21
-1

Use an ngIf on the component

<component-selector *ngIf="someCondition"></component-selector>

And set someCondition to false when you want to destroy it.

Adrian Brand
  • 20,384
  • 4
  • 39
  • 60