angular2仅从字符串

时间:2017-07-16 11:28:42

标签: angular

请告诉我如何在Angular2 / 4中执行以下操作:

组件SomeComponent@Input得到以下html字符串:

  `<am-input
    [placeholder]="'Placeholder'"
    [disabled]="true">
  </am-input>`

SomeComponent如何仅从该字符串中创建一个组件?

感谢

1 个答案:

答案 0 :(得分:3)

唯一的选择是使用JIT编译器并在获得它时进行编译。阅读Here is what you need to know about dynamic components in Angular,特别是Creating components on the fly部分。它详细解释了这个过程。这是要点:

class SomeComponent {
  @Input inputTpl;
  constructor(private _compiler: Compiler,
            private _injector: Injector,
            private _m: NgModuleRef<any>) {
  }

  ngOnChanges() {  
    const tmpCmp = Component({template: inputTpl})(class {});
    const tmpModule = NgModule({declarations: [tmpCmp]})(class {});

    this._compiler.compileModuleAndAllComponentsAsync(tmpModule)
      .then((factories) => {
        const f = factories.componentFactories[0];
        const cmpRef = f.create(this._injector, [], null, this._m);
        cmpRef.instance.name = 'dynamic';
        this.vc.insert(cmpRef.hostView);
      })
    }