繁体   English   中英

Angular-为什么我的简单函数被多次调用?

[英]Angular - Why is my simple function being called many times?

我有一个简单的表,其中使用ngFor显示行。

app.component.html

<table>
    <thead>
        <tr>
            <th>Header 1</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let item of items">
            <td>
                <a>{{myFunc(item?.id) ? "1" : "2"}}</a>
            </td>
        </tr>
    </tbody>
</table>

items是具有一个对象的列表。 我希望myFunc() 仅对 items列表中的一个对象进行一次评估。 但是,似乎myFunc()被调用了4次 ,我也不知道为什么。

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  items = [{"id": 1}];

  myFunc(itemId) {
    console.log("i was called");
    return true;
  }
}

演示此错误的演示: https : //stackblitz.com/edit/angular-j7jgfl “我被叫”被打印到控制台4次。 谁能告诉我为什么以及一次调用该函数的正确方法是什么?

在控制台中,您可以看到以下消息:

Angular在开发模式下运行。 调用enableProdMode()以启用生产模式。

这意味着,Angular在每个周期之后都会以开发模式重新运行更改检测,并在第二次之后检查是否没有任何更改。 如果是这样,将显示警告,因为如果不重新运行可能无法在生产中检测到这些更改。

如果运行enableProdMode(); 在引导之前在文件main.ts (必须在Stackblitz中刷新一次),您会看到该函数的调用频率仅为原来的一半,而两次被调用。

使用默认的ChangeDetectionStrategy时,更改检测将出于多种原因运行。 每次将评估您的功能。 如果您希望更改检测仅运行一次,则将ChangeDetectionStrategy更改为OnPush如下所示:

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  changeDetection: ChangeDetectionStrategy.OnPush
})

现在仅在@Input值更改(对象引用)或已触发事件时运行更改检测。

这是您改进的代码,我不知道我做对与否

 <tr *ngFor="let item of items">
            <td>
                <a>{{myFunc(item) ? "1" : "2"}}</a>
            </td>
        </tr>




myFunc(itemId) {
if(itemId){
console.log("i was called");
    return true;
}else{
return false;
}

  }

也许这会帮助你

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM