ngFor 中调用的方法多次被触发

Ind*_*j26 5 angular angular9

我正在调用 ngFor 中的一种方法来获取输入的标签,即使在 ngFor 中有 2 个项目,它也会触发 8 次。它应该只被调用两次。多次被调用的原因可能是什么?

<form [formGroup]="parentForm">
   <div formGroupName="child">
    <ng-container *ngFor="let item of parentForm.get('child').controls | keyvalue; let i = index">
      <div class="form-group">
      <label>{{getLabel(item.key)}} {{i}} </label>
      <input type="text" [formControlName]="item.key">
      </div>
    </ng-container>
   </div>
  </form>   
Run Code Online (Sandbox Code Playgroud)
  getLabel(item) {
     console.log('trigger item') // its get printed in console for 8 times
  if(item == 'data')  { 
    return 'Your Data' 
  } 
  return 'Your Name'
  }
Run Code Online (Sandbox Code Playgroud)

游乐场:https://stackblitz.com/edit/angular-ivy-hnaegv ?file=src%2Fapp%2Fapp.component.html

Che*_*pan 7

正如 @ukn 在评论中提到的,你不应该在模板上使用函数调用。

\n

每次运行 Angular 变化检测时都会执行 getLabel 函数。

\n

您可以使用管道来避免多个函数调用。让 Angular 知道如果 pipeline\xe2\x80\x99s 输入没有改变,则可以安全地跳过管道的执行

\n
import { Pipe, PipeTransform } from \'@angular/core\';\n\n@Pipe({\n  name: \'getLabel\'\n})\nexport class GetLabelPipe implements PipeTransform {\n\n  transform(value: any, args?: any): any {\n         console.log(\'trigger item\')\n  if(value == \'data\')  { \n    return \'Your Data\' \n  } \n  return \'Your Name\'\n  }\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n

例子

\n