现有以下代码:
Component
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'app';
i = 0;
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
itemChecked(item) {
this.i++;
console.log(item, this.i);
}
}
Template
<ul>
<li *ngFor="let item of data">
{{itemChecked(item)}} {{item}}
</li>
</ul>
页面显示的结果:
Console输出的结果:
页面是按照预期的情况显示的,但是控制台中并不是,也就是说,模板中的ngFor被调用了4次!
这个是什么原因呢? 或者能否避免这种情况呢?
不推荐在模版上直接调用函数,每次变更检测都会执行。