Dynamic ngTemplateOutlet value

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

Something along these 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>

      

It won't work of course, but I think it explains quite well what I'm trying to achieve: if the element is a "div" then it should render the #div template if it "spans" a #span one.

+3


source to share


2 answers


Just specify ngTemplateOutlet

in a variable that is 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 can also specify ngTemplateOutlet

in the function that returns TemplateRef

.

0


source


Wrap an element in parentheses to get it as an expression. *ngTemplateOutlet="(item.ref)"

If it doesn't work, do let item of [ { ref: 'div' }, { ref: 'span'} ]

and use *ngTemplateOutlet="item.ref"

Like Can't get ngTemplateOutlet to work



-1


source







All Articles