如果* ngFor数组中有n个项目,则更改检测将运行n次。为什么?

时间:2019-05-05 10:06:18

标签: angular

在以下代码中,todos有2个项目。单击按钮时,会将added的另一个项目放入数组。

@Component({
  selector: 'app-root',
  template: `
      <button (click)="add()">Add</button>
      <div *ngFor="let todo of todos">
          {{todo.title}} - {{runChangeDetection}}
      </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,

  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  todos = [{ title: 'One' }, { title: 'Two' }];

  add() {
    this.todos = [...this.todos, { title: 'Three' }];
  }
  get runChangeDetection() {
    console.log('TodosComponent - Checking the view');
    return true;
  }

}

stackblitz

我的期望:

当用户单击按钮时,新项目将添加到todos,然后更改检测运行。 CD意识到todos已被更改,因此重新渲染了数组。这样,我希望CD可以运行一次。

现实

如果todos数组中有n个项,则更改检测将运行n次(而不是我期望的1次)。

有人可以提供一些CD见解并解释为什么会发生这种情况吗?

0 个答案:

没有答案