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

前端之家收集整理的这篇文章主要介绍了angularjs – Angular2方法绑定错误:“值在检查后已更改”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在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

原文链接:https://www.f2er.com/angularjs/143465.html

猜你在找的Angularjs相关文章