【问题标题】:<ng-template></ng-template> is loading multiple times<ng-template></ng-template> 正在加载多次
【发布时间】:2018-06-13 22:29:17
【问题描述】:

我正在使用 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>

在我的 component.ts 中:

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

    return this.template2;
}

【问题讨论】:

    标签: angular templates angular2-template angular5 ng-template


    【解决方案1】:
    [ngTemplateOutlet]="loadTemplate()"
    

    导致每次更改检测运行时都会调用loadTemplate()

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

    [ngTemplateOutlet]="myTemplate"
    

    然后更改检测和ngTemplateOutlet 指令可以看到没有更改并且不会重新初始化模板。

    【讨论】:

      【解决方案2】:

      另一种方法是:

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

      【讨论】:

        猜你喜欢
        • 2018-09-14
        • 2023-03-05
        • 2019-02-23
        • 2017-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多