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;
}
One of the main uses for <ng-template> is to hold template content that will be used by Structural directives. Those directives can add and remove copies of the template content based on their own logic. When using the structural directive shorthand, Angular creates an <ng-template> element behind the scenes.
In order to have a template rendered in that container, we use the *ngTemplateOutlet to pass a reference to an existing template, such as the one we created earlier. We use @Input to pass a TemplateRef to our component.
ng-template should be used along with structural directives like [ngIf],[ngFor],[NgSwitch] or custom structural directives. That is why in the above example the contents of ng-template are not displayed. ng-template never meant to be used like other HTML elements.
ng-template is an Angular element that is used for rendering HTML in a template. However, it is not rendered directly on DOM. If you include an ng-template tag to a template, the tag and the content inside it will be replaced by comment upon render.
[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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With