typescript Angular 2:将函数传递给模板上的 ngClass 标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35036961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:14:28  来源:igfitidea点击:

Angular 2: Pass a function to the ngClass tag on the template

angulartypescript

提问by Matt McNabb

I have done some searching on this but haven't come across anything that works.

我已经对此进行了一些搜索,但没有遇到任何有效的方法。

When i pass a function to the ngStyle i get the following error:

当我将函数传递给 ngStyle 时,出现以下错误:

Expression 'getClass()' in ProductView has changed after it was checked.

Expression 'getClass()' in ProductView has changed after it was checked.

My Template looks like:

我的模板看起来像:

<div class="itemContainer">
    <div class="well imageHolder" [ngClass]="getClass()">
        <img [src]="'img/thumbs/' + item.images[0]" class="productImage" id="productImage">
    </div>
</div> 

Im not sure what would fix this or even if it can currently be done. I have noticed that this error also occurs with ngStyle.

我不确定什么会解决这个问题,或者即使它目前可以完成。我注意到这个错误也发生在 ngStyle 中。

All help would be appreciated.

所有帮助将不胜感激。

回答by Liad Livnat

The answer is simple, you can do that with a function, just make sure the function will return the class name

答案很简单,你可以用一个函数来做到这一点,只要确保函数会返回类名

on html:

在 html 上:

<div [ngClass]="getClassByValue('a')"> My Div</div>

on ts file:

在 ts 文件上:

  getClassByValue(value: string) {
    switch (value) {
      case "a": return "class-a";
      case "b": return "class-b";
    }
  }

will end up with class name "class-a" on your element.

将在您的元素上以类名“class-a”结束。

Hope it helps :)

希望能帮助到你 :)

回答by Mark Rajcok

A property binding uses the following syntax: [someProperty]="an Angular template expression".

属性绑定使用以下语法:[someProperty]="an Angular template expression".

In your case, the template expression is a function (rather, than, say, a component property). That's fine. But according to the "Expression Guidelines" section of the Template Syntaxdev guide, expressions must be "idempotent". That means that if the

在您的情况下,模板表达式是一个函数(而不是组件属性)。没关系。但是根据模板语法开发指南的“表达式指南”部分,表达式必须是“幂等的”。这意味着,如果

expression returns a string or a number, it returns the same string or number when called twice in a row. If the expression returns an object (including a Dateor Array), it returns the same object referencewhen called twice in a row.

表达式返回一个字符串或一个数字,它在连续调用两次时返回相同的字符串或数字。如果表达式返回一个对象(包括 aDateArray),则在连续调用两次时它返回相同的对象引用

Since you didn't provide the code for your getClass()function, we'll just assume it is violating the idempotent rule. (You probably return a new array or a new object each time.)

由于您没有为您的getClass()函数提供代码,我们将假设它违反了幂等规则。(您可能每次都返回一个新数组或一个新对象。)

In development mode (which is the default mode), change detection runs twice, and it will catch idempotent violations.

在开发模式(这是默认模式)下,更改检测运行两次,它将捕获幂等违规。

To fix this, return the same array or object reference (but you can modify the array contents or object properties/values). E.g.,

要解决此问题,请返回相同的数组或对象引用(但您可以修改数组内容或对象属性/值)。例如,

export class MyComponent {
   anArray = [];
   getClass() {
      // manipulate (don't reassign) anArray here, and return it
      return this.anArray;
   }
}

回答by Davy

You are not supposed to do this (yes, this probably worked in angular 1.x :) ) The check is there unless you enable production mode:

您不应该这样做(是的,这可能适用于 angular 1.x :))除非您启用生产模式,否则检查就在那里:

https://angular.io/docs/js/latest/api/core/enableProdMode-function.html

https://angular.io/docs/js/latest/api/core/enableProdMode-function.html

My guess (disclaimer: it is a guess ...) is that you are supposed to set literals/variables that reflect the proper state. A variable does not cause side effects, where a method can. I think they enforce this because it helps you preventing too frequent digest loops.

我的猜测(免责声明:这是一个猜测......)是你应该设置反映正确状态的文字/变量。变量不会引起副作用,而方法可以。我认为他们强制执行此操作是因为它可以帮助您防止过于频繁的摘要循环。

So this is the way to go:

所以这是要走的路:

<div class="itemContainer">
    <div class="well imageHolder" [ngClass]="{ 'classA': variableA, 'classB': variableB }">
        <img [src]="'img/thumbs/' + item.images[0]" class="productImage" id="productImage">
    </div>
</div> 

So instead of running some code on each digest loop that checks if the class should be set (and possibly causes new digest loops by altering other stuff), you should set those variables whenever they need to be set.

因此,与其在每个摘要循环上运行一些代码来检查是否应该设置类(并且可能通过更改其他内容导致新的摘要循环),您应该在需要设置这些变量时设置它们。