Dynamic ngTemplateOutlet value

霸气de小男生 提交于 2020-01-24 03:15:14

问题


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.


回答1:


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.




回答2:


Wrap item in parenthesis to get it to evaluate as an expression. *ngTemplateOutlet="(item.ref)" If that doesn't work, do let item of [ { ref: 'div' }, { ref: 'span'} ] and use *ngTemplateOutlet="item.ref" Similar to Can't get ngTemplateOutlet to work



来源:https://stackoverflow.com/questions/43577481/dynamic-ngtemplateoutlet-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!