Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular, get ViewChild / ViewContainerRef from dynamic created Component

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.

like image 453
Hemant Desusa Avatar asked May 26 '17 08:05

Hemant Desusa


People also ask

Which method of ViewContainerRef create an instance of a component?

Descriptionlink. Can contain host views (created by instantiating a component with the createComponent() method), and embedded views (created by instantiating a TemplateRef with the createEmbeddedView() method).

How do I get ViewChild ViewContainerRef?

Get ViewContainerRef with ViewChild: We can use the ViewChild decorator to grab any element in our view and read him as ViewContainerRef . In this example, the container element is the “div” element, and the template will be inserted as a sibling of this “div.”

What is use of @ViewChild in angular?

The @ViewChild decorator allows us to inject into a component class references to elements used inside its template, that's what we should use it for. Using @ViewChild we can easily inject components, directives or plain DOM elements.

What is ViewContainerRef for?

ViewContainerRef represents a container where one or more views can be attached. The first thing to mention here is that any DOM element can be used as a view container. What's interesting is that Angular doesn't insert views inside the element, but appends them after the element bound to ViewContainer .


1 Answers

I am not sure as well how to add viewchild dynamically. however, if dynamic ViewContainerRef is what you want, you can try using this solution:

in the html file create:

  <div id="test"></div>

in your component create:

 let nodeElement = document.getElementById("test");
      let compFactory = this.componentFactoryResolver.resolveComponentFactory(ChildComponent);
      let component = compFactory.create(this.viewContainerRef.injector, null, nodeElement);
like image 89
jay Avatar answered Sep 28 '22 00:09

jay