Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Input while creating Angular 2 Component dynamically using ComponentResolver

I am able to load a dynamic Angular 2 component using ComponentResolver and ViewContainerRef.

However I am not able to figure out how to pass any input variable of child component into this.

parent.ts

    @Component({
     selector: "parent",
     template: "<div #childContainer ></div>"
    })
    export class ParentComponent {
      @ViewChild("childContainer", { read: ViewContainerRef }) childContainer: ViewContainerRef;

      constructor(private viewContainer: ViewContainerRef, private _cr: ComponentResolver) {}

      loadChild = (): void => {
           this._cr.resolveComponent(Child1Component).then(cmpFactory => {               
              this.childContainer.createComponent(cmpFactory);
           });
      }
    }

child1

 @Component({
   selector: "child1",
   template: "<div>{{var1}}</div><button (click)='closeMenu()'>Close</button>"
 })
 export class Child1Component {
    @Input() var1: string;
    @Output() close: EventEmitter<any> = new EventEmitter<any>();

    constructor() {}

    closeMenu = (): void => {
      this.close.emit("");
    }
 }

so in above example say loadChild is being called on a button click, I am able to load Child1Component, but how to pass var1 Input of child? Also How to subscribe to close EventEmitter decorated with @Output

like image 892
Madhu Ranjan Avatar asked May 27 '16 16:05

Madhu Ranjan


2 Answers


You have to pass it imperatively like:

loadChild(): void {
  this._cr.resolveComponent(Child1Component).then(cmpFactory => {               
    let cmpRef = this.childContainer.createComponent(cmpFactory);
     cmpRef.instance.var1 = someValue;  
   });
 }

also similar with registering handlers for outputs.

loadChild(): void {
  this._cr.resolveComponent(Child1Component).then(cmpFactory => {                
    let instance: any = this.childContainer.createComponent(cmpFactory).instance;
    if (!!instance.close) {
      // close is eventemitter decorated with @output 
      instance.close.subscribe(this.close);
    }
  });
}

close = (): void => {
  // do cleanup stuff..
  this.childContainer.clear();
}
like image 59
Günter Zöchbauer Avatar answered Oct 01 '22 19:10

Günter Zöchbauer


This is how I did it with Angular 2.2.3

let nodeElement = document.getElementById("test");
let compFactory = this.componentFactoryResolver.resolveComponentFactory(AnyCustomComponent);
let component = compFactory.create(this.viewContainerRef.injector, null, nodeElement);
// This is where you pass the @Input
component.instance.anyInput = anyInput;
like image 6
S.Galarneau Avatar answered Oct 01 '22 19:10

S.Galarneau