<ng-template> </ng-template> loads several times

I am using ngTemplateOutlet to download. but it loads the template several times. It loads the correct template, but executes the loadTemplate () method several times.

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;
}
+4
source share
2 answers
[ngTemplateOutlet]="loadTemplate()"

calls loadTemplate()for a call at each start of change detection.

Rather, assign the result loadTemplate()to a field and use this field in a binding

[ngTemplateOutlet]="myTemplate"

then change the definition and the directive ngTemplateOutletwill see that there were no changes and will not reinitialize the template.

+4
source

:

<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>
0

Source: https://habr.com/ru/post/1691723/


All Articles