【问题标题】:ngClass function inside ngFor issuengFor 问题中的 ngClass 函数
【发布时间】: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;
    }

  }
}

jsfiddle

当我点击按钮时,“test2”工作正常(它只被调用了 1 次),但“test1”(来自ngClass 中的函数)被调用了 5 次,即使使用了断路器。

我猜这是由于ngClass,但我怎样才能让它只被点击的元素调用?

【问题讨论】:

  • 在每种情况下,我都在开发工具控制台中看到“test2”仅打印一次

标签: javascript html angular ngfor ng-class


【解决方案1】:

每次 Angular 运行变更检测时都会调用视图绑定中的函数,因此通常被认为是个坏主意。

首选方法是将函数调用的结果分配给一个字段并绑定到该字段。 如果您使用*ngFor,您通常需要一个包含值数组的字段。

使用绑定到它

<div class="button" *ngFor="let button of buttons; index as i">
<button [ngClass]="{'red': testColors[i]"
                (click)="changeColor(button.id)">
        test {{button.id}} - {{button.color}}
</button>
</div>

【讨论】:

  • 其实这和我做的没什么区别。写它的正确方法是“让 i = index”,但它不会改变任何东西。在这种情况下 index 或 button.id 具有相同的值。在我的真实代码中,函数 testColors() 比这大得多,我想避免多次调用它
  • 在我的示例中,testColors 应该是一个数组,而不是我的回答中解释的函数。我不明白你试图用你的颜色来完成什么,因此没有尝试想出代码来创建一个数组。
  • 好的,我明白你的意思了。但这不是我的问题。我的问题是:当我在 ngClass 中有一个测试函数时,它被调用了 5 次。我怎么能叫它1次。有可能吗?
  • 这不可能,而且绝对是错误的方法。我可能会认为有一些方法可以实现这一点,但那是高级更改检测调整。无论如何,当您更好地理解 CD 时,您可以稍后调整它,但是将函数的结果绑定到属性或属性,特别是如果函数所做的不仅仅是最基本的计算,这并不是您使用 Angular 绑定的方式。
  • Angular 每次运行更改检测时都会调用该函数,对此您无能为力,您所能做的就是限制运行更改检测的时间,但是对于您的用例,这已经是当更改检测应该运行时,“手动”控制相当复杂。
【解决方案2】:

这是因为你的控制台在for中,所以中断按预期工作,如果你点击第一个按钮,它会在一次迭代后停止,但如果你点击第五个,它会在第五个之后中断。

反正for没用,你可以这样做:

testColor(id){
  return this.buttons[id].color;
}
changeColor(id){
  this.buttons[id].color = !this.buttons[id].color;
}

你甚至可以跳过 testColor:

<button [class.red]="button.color" (click)="changeColor(button.id)"> 
    test {{button.id}} - {{button.color}}
</button>

【讨论】:

  • 好吧,控制台显示5“测试1”,我希望它只显示一个。此外,您的代码也是如此,函数 testColor() 被调用了 5 次。
  • 我用更好更轻的方法更新了我的答案!
猜你喜欢
  • 2016-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-01
  • 2023-01-27
  • 1970-01-01
  • 2019-07-05
  • 2018-10-18
相关资源
最近更新 更多