By Kevin

2018-10-11 03:47:27 8 Comments

I am using Angular 2 +

parent component


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

template .html :

<div [routerLink]="['product/']" ></div>
<!--When user click this DOM, the child component(ProductDetailComponent) will be loaded and navigated..  -->


Child Component


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.

   //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;





@Kevin 2018-12-20 02:56:34

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

@Adrian Brand 2018-10-11 04:14:26

Use an ngIf on the component

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

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

Related Questions

Sponsored Content

43 Answered Questions

[SOLVED] JavaScript closure inside loops – simple practical example

38 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

34 Answered Questions

[SOLVED] How do I return the response from an asynchronous call?

17 Answered Questions

3 Answered Questions

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

53 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

79 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5717828 View
  • 7111 Score
  • 79 Answer
  • Tags:   javascript arrays

54 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

Sponsored Content