动态ngTemplateOutlet值 [英] Dynamic ngTemplateOutlet value

查看:118
本文介绍了动态ngTemplateOutlet值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以动态设置* ngTemplateOutlet指令的值?

Is there a way to dynamically set the value of the *ngTemplateOutlet directive?

遵循这些原则:

<div *ngFor="let item of [ 'div', 'span' ]">
  <ng-container *ngTemplateOutlet="{{ item }}"></ng-container>
</div>

<ng-template #div>
  <div>some text inside a div</div>
</ng-template>

<ng-template #span>
  <span>some text inside a span</span>
</ng-template>

当然它不起作用,但是我想它很好地解释了我要实现的目标:如果项目是"div",那么它应该显示#div模板,如果它是"span",则#span一个.

Of course it doesn't work but I guess it explains quite well what I'm trying to achieve: if the item is "div", then it should display the #div template, if it's "span" the #span one.

推荐答案

ngTemplateOutlet指向变量TemplateRef:

在HTML中:

<button (click)="toggleTemplateSelected()">Toggle Template</button>
<br />
<p>Showing 
  <span class='viewType' *ngIf="showViewTemplate">C</span>
  <span class='viewType' *ngIf="!showViewTemplate">C2</span> 
  template:</p>
<ng-container *ngTemplateOutlet='liveTemplate'></ng-container>

<!--Templates: -->
<ng-template #tmplC>
  Hello from TemplateC
</ng-template>

<ng-template #tmplC2>
  Hello from TemplateC2
</ng-template>

在代码中:

@ViewChild('tmplC') tmplC: TemplateRef<any>;
@ViewChild('tmplC2') tmplC2: TemplateRef<any>;

showViewTemplate = true;
liveTemplate: TemplateRef<any>;

toggleTemplateSelected() {
    this.showViewTemplate = !this.showViewTemplate;
    this.liveTemplate = this.showViewTemplate ? this.tmplC : this.tmplC2;
}

您还可以将ngTemplateOutlet指向返回TemplateRef的函数.

You could also point ngTemplateOutlet at a function that returns a TemplateRef.

这篇关于动态ngTemplateOutlet值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆