加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 09:03:56 所属栏目:安全 来源:网络整理
导读:我已经对此做了一些搜索,但没有发现任何有用的东西. 当我将函数传递给ngStyle时,我得到以下错误: ProductView中的表达式’getClass()’在检查后发生了变化. 我的模板看起来像: div class="itemContainer" div class="well imageHolder" [ngClass]="getClas
我已经对此做了一些搜索,但没有发现任何有用的东西.

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

ProductView中的表达式’getClass()’在检查后发生了变化.

我的模板看起来像:

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

我不知道什么会解决这个问题,即使目前可以做到这一点.我注意到ngStyle也会出现这个错误.

所有帮助将不胜感激.

属性绑定使用以下语法:[someProperty] =“一个Angular模板表达式”.

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

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 Date or Array),it returns the same object reference when called twice in a row.

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

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读