Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<ng-template></ng-template> is loading multiple times

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;
}
like image 269
Rajasekar Sambandam Avatar asked Jan 04 '18 08:01

Rajasekar Sambandam


People also ask

What is the job of ng-template ></ ng-template >?

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.

How do I pass a ng-template?

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.

Can I use ng-template without ngIf?

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.

What is HTML ng-template?

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.


1 Answers

[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.

like image 78
Günter Zöchbauer Avatar answered Sep 30 '22 00:09

Günter Zöchbauer