angular2中的递归动态模板编译

时间:2016-09-29 13:18:54

标签: angular typescript compilation angular2-compiler

我的一些工作基于此处描述的相同问题:

使用Angular 2.0编译动态组件的动态模板

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

可以找到上述问题中描述的工作人员here

如果动态详细信息尝试创建另一个在模板中使用动态详细信息的动态视图,则会出现此问题。如果我尝试这样做,我会得到以下异常。:

'dynamic-detail'不是已知元素: 1.如果'dynamic-detail'是Angular组件,请验证它是否是此模块的一部分。

通过更改plunker中的逻辑来创建一个输出“<dynamic-detail></dynamic-detail>”的动态模板,可以轻松地重新进行重新播放。

在文件“ app / dynamic / template.builder.ts ”中,我更改了以下代码:

      let editorName = useTextarea 
    ? "text-editor"
    : "string-editor";

      let editorName = useTextarea 
    ? "dynamic-detail"
    : "string-editor";

当发生这种情况时,我会遇到上述异常。显然,编译器在递归完成时不熟悉动态细节。

我试图将DynamicDetail添加到不同模块中的导入而没有任何运气。也许这不是解决方案的一部分。

1 个答案:

答案 0 :(得分:2)

如果您将"text-editor"更改为"dynamic-detail",那么您的模板将如下所示:

<form>
  <dynamic-detail
     [propertyName]="'code'"
     [entity]="entity"
   ></dynamic-detail>
   <dynamic-detail
      [propertyName]="'description'"
      [entity]="entity"
   ></dynamic-detail>
</form>

DynamicDetail组件没有propertyNameentity属性。 所以你可以添加他们的。

<强> detail.view.ts

export class DynamicDetail implements AfterViewInit, OnChanges, OnDestroy, OnInit
{ 
    @Input()  public propertyName: string;
    @Input()  public entity: any;

解决方案的第二部分是将此组件添加到RuntimeComponentModule

<强> type.builder.ts

protected createComponentModule (componentType: any) {
  @NgModule({
    imports: [ 
      PartsModule,
      DynamicModule.forRoot() // this line
    ],
    declarations: [
      componentType
    ],
  })
  class RuntimeComponentModule {}

  return RuntimeComponentModule;
}

之后它应该有效 Plunker Example