我尝试使用
调用ngfor中的方法*ngFor=" let day of Days()" >{{day}}
方法:
Days(){
console.log("check");
return [1,2,3,4,5,6,7];
}
它执行一次模板,但问题是它在控制台中登录3次"检查"。 为什么它会调用这个函数3次?
模板
<div class="table-responsive">
<table class="table table-bordered year">
<tr>
<td *ngFor=" let day of Days()" >{{day}}</td>
</tr>
</table>
</div>
控制器
export class MonthComponent{
//public num: number;
public lastday: number;
num = 1;
Days(){
console.log("check");
return [1,2,3,4,5,6,7];
}
getDays(){
if( this.num == 1 ){
let j=1;
let d = new Date();
let day = d.getDay();
let today = d.getDate();
let dif = today % 7;
let days = [];
if( day - dif <0){
dif = day - dif + 8;
}
else dif = day-dif;
for (let i = 0; i != 7; i+=1) {
if(i < dif-1) days.push(31-dif+i+2);
else {
days.push(j);
j+=1;
}
//console.log(days);
}
this.lastday = j-1;
this.num +=1;
console.log(days);
return days;
}
else{
let j = this.lastday;
let days = []
for (var i = 0; i < 7;i+=1) {
j +=1;
days.push(j)
}
this.lastday = j;
console.log(days);
console.log(this.num);
this.num +=1;
return days;
}
}
}
Days()是测试函数,实际上我需要getDays()
答案 0 :(得分:2)
尽量避免在绑定中使用函数/方法。每次运行更改检测时,Angular2更改检测都会执行它们。
因为每次调用都会从Days()
返回一个不同的数组实例Angular2变化检测抛出&#34;&#34;表达式在检查后发生了变化。&#34;因为这种方式变化检测无法确定何时模型已经解决,因为每次更改检测检查它已经改变(它不会检查数组的内容,只检查对象标识)
要解决此问题,请将函数的结果分配给属性,并在绑定中使用此属性:
class MyComponent {
constructor() {
this.Days();
}
days:<number>[];
Days(){
console.log("check");
this.days = [1,2,3,4,5,6,7];
}
}
<div class="table-responsive">
<table class="table table-bordered year">
<tr>
<td *ngFor=" let day of days" >{{day}}</td>
</tr>
</table>
</div>