如何在 Angular 2 中动态渲染模板?

Lih*_*hai 3 javascript angular

我试图通过使用 Angular 2 的传统“#”字符引用它们来在视图中动态选择模板。在我的项目中,我处理错误并将它们显示给用户,我有一个对话框组件,它的内容应该基于动态 html注入,这就是为什么我使用模板。

我阅读了一些文章,这些文章展示了一种方法,当我已经知道模板引用的名称时,我不知道引用的名称,我在运行时得到了名称。我特别遵循了本指南:https : //www.bennadel.com/blog/3101-experimenting-with-dynamic-template-rendering-in-angular-2-rc-1.htm

所以目前我的对话框组件具有以下视图:

<template #err_1 let-property1="p1" let-property2="p2">
property1: {{p1}}
property2: {{p2}}

</template>

<template #err_2 let-property1="p1" let-property2="p2">
<p *ngIf="p1">{{p1}}</p>
property2: {{p2}}
</template>

<!--The code for the template directive i took from the guide in the link above-->
<tem [render]="templateRef"
     [context]="context">
</tem>
Run Code Online (Sandbox Code Playgroud)

在我的 dialog.ts 我有以下代码:

@Component({
  selector: 'error-dialog',
  queries: {
    templateRef: new ViewChild("err_1")
  },
  templateUrl: './dialog.html'
})
...
Run Code Online (Sandbox Code Playgroud)

“TemplateRendererDirective”指令源是我从上面链接中的指南中获取的。注意是什么让我感到困惑:templateRef 基本上得到一个对象:“ViewChild”,即使指令最终得到 TemplateRef 实例,这怎么可能?

所以只有当我知道我想要呈现哪个错误模板时,例如:“err_1”我只是在 dialog.ts 中预先引用它,但事实并非如此,我想动态地告诉我想要呈现“err_1”、“err_2”等.. 并给出上下文(这是用数据填充该模板的对象 - 例如 p1、p2,也是动态的)

有可能做到吗?

yur*_*zui 5

正如我在评论中提到的,您可以尝试使用@ViewChildren它来工作。但是我使用附加指令TemplateNameDirective来操作模板的name.

这是它的外观:

@Directive({
  'selector': 'template[name]'
})
export class TemplateNameDirective {
  @Input() name: string;
  constructor(public templateRef: TemplateRef<any>) {}
}

@Component({
  selector: 'error-dialog',
  template: `
    <template name="err_1" let-item>
      property1: {{item.p1}}
      property2: {{item.p2}}
    </template>

    <template name="err_2" let-item>
      <p *ngIf="item.p1">{{item.p1}}</p>
      property2: {{item.p2}}
    </template>

    <!-- 
       I use ngTemplateOutlet directive 
       https://angular.io/docs/ts/latest/api/common/index/NgTemplateOutlet-directive.html 
    -->
    <template [ngTemplateOutlet]="templateRef" [ngOutletContext]="{ $implicit: context }">
    </template>
  `
})
export class ErrorDialogComponent {
  @ViewChildren(TemplateNameDirective) children: QueryList<TemplateNameDirective>;

  templateRef: TemplateRef<any>;
  context: any;

  public setContent(errTemplateName, context) {
    this.templateRef = this.children.toArray()
      .find(x => x.name === errTemplateName).templateRef; 
    this.context = context;
  }
}
Run Code Online (Sandbox Code Playgroud)

父视图:

<error-dialog #dialogRef></error-dialog>
<button (click)="dialogRef.setContent('err_1', { p1: 'test'})">Test err_1</button>
<button (click)="dialogRef.setContent('err_2', { p2: 'test2'})">Test err_2</button>
Run Code Online (Sandbox Code Playgroud)

Plunker 示例

注意:我正在传递ngOutletContext带有$implicit属性的对象。

在上下文对象中使用键 $implicit 会将其值设置为默认值。

它的工作原理如下:

[ngOutletContext]="{ $implicit: row }"  ==> <template let-row>

[ngOutletContext]="{ item: row }"       ==> <template let-row="item">
Run Code Online (Sandbox Code Playgroud)