【发布时间】:2018-08-01 11:05:44
【问题描述】:
这是一个非常简单的ngForloop。
html:
<div class="button" *ngFor="let button of buttons">
<button [ngClass]="{\'red\': testColor(button.id)}"
(click)="changeColor(button.id)">
test {{button.id}} - {{button.color}}
</button>
</div>
JS:
testColor(id){
for(let i=0; i<this.buttons.length; i++){
if(id == i){
console.log('test1');
return this.buttons[i].color;
break;
}
}
}
changeColor(id){
for(let i=0; i<this.buttons.length; i++){
if(id == i){
console.log('test2');
this.buttons[i].color = !this.buttons[i].color;
break;
}
}
}
当我点击按钮时,“test2”工作正常(它只被调用了 1 次),但“test1”(来自ngClass 中的函数)被调用了 5 次,即使使用了断路器。
我猜这是由于ngClass,但我怎样才能让它只被点击的元素调用?
【问题讨论】:
-
在每种情况下,我都在开发工具控制台中看到“test2”仅打印一次
标签: javascript html angular ngfor ng-class