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

angularjs – Angular2方法绑定错误:“值在检查后已更改”

发布时间:2020-12-17 07:53:45 所属栏目:安全 来源:网络整理
导读:我想在Angular2中制作一个圆形板.例如,我想制作10个圆圈,但实际上这个数字可以改变.我想计算每个圆的半径,所以它是动态的而不是静态的.如图 所示 这是我的代码 @Component({ selector:"circle" template: ` svg circle *ngFor='#item of forLength #i=index
我想在Angular2中制作一个圆形板.例如,我想制作10个圆圈,但实际上这个数字可以改变.我想计算每个圆的半径,所以它是动态的而不是静态的.如图 所示

这是我的代码

@Component({
    selector:"circle"
    template: `
  <svg>
    <circle *ngFor='#item of forLength #i=index #l=last #e=even'
            cx="50%" cy="50%" [style.r]="calculateRadius()" stroke="black" stroke-width="5" fill="white"></circle>
  <svg/>  
    `
})

export class CircleComponent{
    public maxRadius:number=25;
    public totalRounds:number=10;
    public x:number=30;

    public calculateRadius():number{
        var distanceBetweenCircles=this.maxRadius/(this.totalRounds-1);
        this.x-= distanceBetweenCircles;
        return this.x;
    }
}

但是我收到以下错误:

calculateRadius() in CircleComponent@7:30' has changed after it was checked. 
    Previous value: '-7.500000000000007'. 
    Current value: '-36.66666666666668' in [calculateRadius() in CircleComponent@7:30]

是否有更好的方法可以使用* ngFor编写此for循环而不是在单独的方法中编写它?

在开发模式(默认)下,更改检测为 run twice,以确保模型更改已稳定.这意味着ngFor循环被评估两次.因此,属性x将在第二次更改检测运行时继续递减.您应用中的其他活动也会导致更改检测运行,并且x将继续递减.因此,您必须编写所有视图函数,例如calculateRadius(),假设它们将被执行多次.例如.:
public calculateRadius(i):number{
    return this.x - i*this.distanceBetweenCircles;
}

模板语法开发指南在描述idempotent expressions时提到了这一点.

这也将解决在检查问题后已经改变的值.

您还需要使用以下语法绑定SVG属性r:[attr.r] =“…”,而不是[style.r] =“…”.

Plunker

(编辑:李大同)

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

    推荐文章
      热点阅读