Madhu Ranjan Madhu Ranjan - 1 year ago 2480
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.


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 => {


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 => {

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

Thanks in advance!

Answer Source

You have to pass it imperatively like:

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

also similar with registering handlers for outputs.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download