简体   繁体   中英

Destroy/Remove dynamically a component from the child

I want to remove the OverviewComponent from ExploreComponent when it is clicked.

There is how I add this component:

export class ExploreComponent implements OnInit {

  constructor(public viewContainerRef: ViewContainerRef) { }

  ngOnInit(): void { }

  onItemSelected() {
    this.viewContainerRef.createComponent(OverviewComponent);
  }
}
export class OverviewComponent implements OnInit {

  constructor() { }

  ngOnInit(): void { }

  onClose() {
    ...
  }
}

Use the clear method to clear that component.

this. viewContainerRef.clear();

I finally found a solution myself and for those who have the same problem there is how to do:

So I couldn't add an event on my component HTML element because it was dynamically added.

<app-challenge-overview (closeEvent)="onCloseFromChild($event)"></app-challenge-overview>

So the solution was to get the createComponent(...) value and to subscribe an event like following.

const componentRef = this.viewContainerRef.createComponent(OverviewComponent);
componentRef.instance.closeEvent.subscribe(() => {
    this.closeOverview();
});

Hope it helped someone:)

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