Angular, get ViewChild / ViewContainerRef from dynamic created Component

Viewed 7489

is there a way to get the ViewContainerRef from a dynamic created component? My dynamic created component has an ngContent element inside, which i want to fill after the dynamic creation.

export class Example {

  @ViewChild('content', { read: ViewContainerRef }) //normal way
  content: ViewContainerRef;

...

  ngAfterViewInit(){
    let box1=this.content.createComponent(this.boxFactory);
    box1.instance.title="Dynamic (1)";
    // HERE: the box1 has a ng-content area which i want to fill.
  }

}

I think about some manual way to resolve the ViewChild instead of using the decorators. Some Ideas?

Thanks a lot.

3 Answers

Dynamically Created Component

export class DashPanelComponent implements OnInit {

  @ViewChild('dashpanelpos', { read: ViewContainerRef }) dashPanelPosition?: ElementRef;

  constructor() { }
  ngOnInit() {  }

}

To access ViewContainerRef

this.dashPanel = this.renderComp({}, this.contentMappings["dash_panel"], container);
this.viewContainerRef = this.dashPanel.instance["dashPanelPosition"]);

dashPanelPosition is instance of DashPanelComponent.

Related