问题描述
有没有办法动态设置 *ngTemplateOutlet 指令的值?
类似的东西:
<ng-container *ngTemplateOutlet="{{ item }}"></ng-container><ng-template #div><div>div 中的一些文本</div></ng-模板><ng-template #span><span>跨度内的一些文本</span></ng-模板>
当然它不起作用,但我想它很好地解释了我想要实现的目标:如果项目是div",那么它应该显示#div 模板,如果它是span"#span一个.
只需将 ngTemplateOutlet
指向一个 TemplateRef
变量:
在 HTML 中:
<button (click)="toggleTemplateSelected()">切换模板</button><br/><p>显示<span class='viewType' *ngIf="showViewTemplate">C</span><span class='viewType' *ngIf="!showViewTemplate">C2</span>模板:<ng-container *ngTemplateOutlet='liveTemplate'></ng-container><!--模板:--><ng-模板#tmplC>你好来自 TemplateC</ng-模板><ng-模板#tmplC2>你好来自 TemplateC2</ng-模板>
在代码中:
@ViewChild('tmplC') tmplC: TemplateRef;@ViewChild('tmplC2') tmplC2: TemplateRef;showViewTemplate = true;liveTemplate: TemplateRef;切换模板选择(){this.showViewTemplate = !this.showViewTemplate;this.liveTemplate = this.showViewTemplate ?this.tmplC : this.tmplC2;}
您还可以将 ngTemplateOutlet
指向返回 TemplateRef
的函数.
Is there a way to dynamically set the value of the *ngTemplateOutlet directive?
Something along those lines:
<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>
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.
Just point ngTemplateOutlet
at a variable that is a TemplateRef
:
In 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>
In code:
@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;
}
You could also point ngTemplateOutlet
at a function that returns a TemplateRef
.
这篇关于动态 ngTemplateOutlet 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!