Angular2 - Pass values to a dynamic component created with ComponentFactory

笑着哭i 提交于 2019-12-06 05:19:12

问题


I was following Günter Zöchbauer's advice on how to create dynamic components and I was wondering how I could pass values to it - as in, the child component has an @input.

Using the plunker example given in the above question - plunker - how could I pass the child component a string, lets call it message, that would then display when clicking the 'add' button.

Here's an example of how the child component might look:

import {Component OnChanges, Input} from '@angular/core'

    @Component({
      selector: 'hello',
      providers: [],
      template: `<h1>{{message}}</h1>`,
      directives: []
    })
    export class HelloComponent implements OnChanges {
      @Input() message:any;

      constructor() {
      }

      ngOnChanges(changes:any){
      }
    }

回答1:


You can try below,

  let instance  = this.viewContainerRef.createComponent(this.componentFactory, 0).instance;
  instance.message = "some text!!";

Here is the Plunker!!

Hope this helps!!



来源:https://stackoverflow.com/questions/39048769/angular2-pass-values-to-a-dynamic-component-created-with-componentfactory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!