Madhu Ranjan Madhu Ranjan - 6 months ago 1420
AngularJS Question

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


Thanks in advance!

Answer

You have to pass it imperatively like:

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

also similar with registering handlers for outputs.