【问题标题】:angular2 generate component from just a stringangular2 仅从字符串生成组件
【发布时间】:2017-12-21 00:48:50
【问题描述】:

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

组件SomeComponent@Input获取以下html作为字符串:

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

SomeComponent 如何仅从该字符串在其内部创建一个组件?

谢谢

【问题讨论】:

  • @Aravind 你给出的例子 - 他们有简单的 html 字符串,而不是之前必须由 angular 处理的 html。或者这对 DomSanitize 来说无关紧要?

标签: angular


【解决方案1】:

唯一的选择是使用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);
      })
    }

【讨论】:

  • 我收到以下错误:ERROR Error: Template parse errors: Can't bind to 'placeholder' since it isn't a known property of 'am-input'. 但我在parent module 中导入了am-input module。虽然如果我传递给 Component()(class {}) 而不是空类 - the exact component class(我正在尝试动态生成)并且与 NgModule(..)(AmInputModule) 相同 - 一切都很好。但是有很多组件可以通过@Input 传递。如果我不仅需要传递代码,还需要传递组件和模块类,这听起来很可悲。我怎样才能避免这种情况?
  • @AndreyPonomarenko,你能把你的代码放在问题细节中还是更好地创建一个 plunker?
猜你喜欢
  • 2012-08-16
  • 2011-12-02
  • 2018-07-26
  • 1970-01-01
  • 2016-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多