在以下代码中,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;
}
}
我的期望:
当用户单击按钮时,新项目将添加到todos
,然后更改检测运行。 CD意识到todos
已被更改,因此重新渲染了数组。这样,我希望CD可以运行一次。
现实
如果todos
数组中有n个项,则更改检测将运行n次(而不是我期望的1次)。
有人可以提供一些CD见解并解释为什么会发生这种情况吗?