<ng-template> </ ng-template>正在加载多次

Raj*_*dam 4 templates angular2-template ng-template angular angular5

我正在使用ngTemplateOutlet加载。但是它会多次加载模板。正在加载正确的模板,但会多次执行loadTemplate()方法。

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>
Run Code Online (Sandbox Code Playgroud)

在我的component.ts中

@ViewChild('template1') template1: TemplateRef<any>;
@ViewChild('template1') template1: TemplateRef<any>;
loadTemplate(){
    if (condition)
        return this.template1;

    return this.template2;
}
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 5

[ngTemplateOutlet]="loadTemplate()"
Run Code Online (Sandbox Code Playgroud)

loadTemplate()每次更改检测运行时都会调用原因。

而是将结果分配loadTemplate()给一个字段并在绑定中使用该字段

[ngTemplateOutlet]="myTemplate"
Run Code Online (Sandbox Code Playgroud)

然后进行更改检测,该ngTemplateOutlet指令可以看到没有更改,也不会重新初始化模板。