Reputation: 169
I am using ngTemplateOutlet to load . but It loads a template multiple times .It is loading correct template but it executing multiple times loadTemplate() method.
In HTML:
<table>
<thead>
</thead>
<tbody>
<ng-template [ngTemplateOutlet]="loadTemplate()"></ng-template>
</tbody>
</table>
<ng-template #template1>
<tr *ngFor="iteration">
<p>Hiii</p>
</tr>
</ng-template>
<ng-template #template2>
<tr *ngFor="iteration">
<p>Byee</p>
</tr>
</ng-template>
In my component.ts:
@ViewChild('template1') template1: TemplateRef<any>;
@ViewChild('template1') template1: TemplateRef<any>;
loadTemplate(){
if (condition)
return this.template1;
return this.template2;
}
Upvotes: 7
Views: 4830
Reputation: 164
Another approach would be:
<table>
<thead>
</thead>
<tbody>
<ng-template [ngTemplateOutlet]="condition ? template1 : template2"></ng-template>
</tbody>
</table>
<ng-template #template1>
<tr *ngFor="iteration">
<p>Hiii</p>
</tr>
</ng-template>
<ng-template #template2>
<tr *ngFor="iteration">
<p>Byee</p>
</tr>
</ng-template>
Upvotes: 1
Reputation: 657118
[ngTemplateOutlet]="loadTemplate()"
causes loadTemplate()
to be called every time change detection runs.
Rather assign the result of loadTemplate()
to a field and use that field in binding
[ngTemplateOutlet]="myTemplate"
then change detection and the ngTemplateOutlet
directive can see that there was no change and won't re-initialize the template.
Upvotes: 11