[英]<ng-template></ng-template> is loading multiple times
I am using ngTemplateOutlet to load . 我正在使用ngTemplateOutlet加载。 but It loads a template multiple times .It is loading correct template but it executing multiple times loadTemplate() method.
但它多次加载一个模板。它正在加载正确的模板,但它执行多次loadTemplate()方法。
In HTML : 在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 : 在我的component.ts中 :
@ViewChild('template1') template1: TemplateRef<any>;
@ViewChild('template1') template1: TemplateRef<any>;
loadTemplate(){
if (condition)
return this.template1;
return this.template2;
}
[ngTemplateOutlet]="loadTemplate()"
causes loadTemplate()
to be called every time change detection runs. 每次更改检测运行时都会调用
loadTemplate()
。
Rather assign the result of loadTemplate()
to a field and use that field in binding 而是将
loadTemplate()
的结果分配给字段并在绑定中使用该字段
[ngTemplateOutlet]="myTemplate"
then change detection and the ngTemplateOutlet
directive can see that there was no change and won't re-initialize the template. 然后更改检测,
ngTemplateOutlet
指令可以看到没有更改,也不会重新初始化模板。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.