使用ComponentResolver动态创建Angular 2组件时传递输入 [英] Passing Input while creating Angular 2 Component dynamically using ComponentResolver

查看:66
本文介绍了使用ComponentResolver动态创建Angular 2组件时传递输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够使用ComponentResolver和ViewContainerRef加载动态Angular 2组件.

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("");
    }
 }

因此在上面的示例中,说单击按钮时调用了loadChild,我能够加载Child1Component,但是如何传递var1子项的输入? 另请参见如何订阅装饰有@Output

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

推荐答案


您必须像这样通过命令:


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();
}

这篇关于使用ComponentResolver动态创建Angular 2组件时传递输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆