3

我想在 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 也可以工作。

4

1 回答 1

1

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

对于这种类型的用例,您应该使用模板出口。

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


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

官方 Angular 文档ngTemplateOutlet或关于 ngTemplateOutlet
的精彩博客文章

于 2018-04-05T04:47:19.513 回答