【问题标题】:Add ng-template Dynamically动态添加 ng-template
【发布时间】:2018-09-14 19:01:51
【问题描述】:

我想在 HTML 中动态添加以下内容。

<ng-template #elseblock *ngIf="var">
    <h1>
        {{heading}}
    </h1>
</ng-template>

我正在使用以下方法。

在 app.component.ts 文件中:

htmldata: any = `<ng-template #elseComponent *ngIf="var">
<h1>
  {{ heading }}
</h1>

`;

在 app.component.html 中

 <div [innerHTML]="htmldata"> </div>

但是这个方法只在 DOM 中渲染 h1 标签。(没有 ng-template)

请帮我动态添加 ng-template,以便 #else 块,*ngIf 也可以工作。

【问题讨论】:

标签: angular angular5 angular2-template ng-template


【解决方案1】:

根据我对您问题的理解,您想做内容投影。

你应该为这种类型的用例使用模板出口。

<ng-template #heading let-heading>
  <h1>
    {{heading}}
  </h1>
</ng-template>


<ng-container *ngTemplateOutlet="heading; context: ContextObj">
</ng-container>

Angular 官方文档ngTemplateOutlet
ngTemplateOutlet 上的精彩博文

【讨论】:

    猜你喜欢
    • 2018-07-03
    • 2018-06-13
    • 2023-04-10
    • 1970-01-01
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 2013-04-22
    • 2020-09-05
    相关资源
    最近更新 更多