Home > front end >  Access parent method from a dynamically added child
Access parent method from a dynamically added child

Time:08-08

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() {
    ...
  }
}

CodePudding user response:

Use the clear method to clear that component.

this. viewContainerRef.clear();

CodePudding user response:

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 :)

  • Related