angular - 使用 ComponentResolver 动态创建 Angular 2 组件时传递输入

标签 angular typescript

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

但是我无法弄清楚如何将子组件的任何输入变量传递给它。

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

child 1

 @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

修饰的close EventEmitter

最佳答案


你必须像这样命令式地传递它:

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

也类似于为输出注册处理程序。

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

关于angular - 使用 ComponentResolver 动态创建 Angular 2 组件时传递输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37487977/

相关文章:

javascript - 为什么我在 React 应用程序中失去了登录信息?

typescript - 使用未定义的值在 Typescript 中进行解构

Angular 6 ServiceWorker - index.html 返回响应 404 Not Found

java - 将嵌套对象从 Angular 发布到 Spring REST API 始终为 null

Angular Material 虚拟滚动不在单元测试中渲染项目

typescript - 对象解构中的类型

css - 在 Angular 2 应用程序中跨组件共享样式

twitter-bootstrap - Angular2 网页包 : how to import bootstrap css

angular - Nativescript - 我的组件中不存在 ChangeDetectorRef

javascript - 如何解决我的 TypeScript/ESLint/Webpack 转译问题