angularjs - Angular2方法绑定(bind)错误: "value has changed after it was checked"

标签 angularjs data-binding typescript angular

我正在尝试在 Angular2 中制作一个圆板。例如,我想制作 10 个圆圈,但实际上这个数字可以改变。我想计算每个圆的半径,所以它是动态的而不是静态的。例如看图片enter image description here

这是我的代码

@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 将继续递减。因此,您必须编写所有 View 函数,如 calculateRadius(),假设它们将被执行多次。例如:

public calculateRadius(i):number{
    return this.x - i*this.distanceBetweenCircles;
}

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

这也将解决 value has changed after it was checked 问题。

您还需要使用以下语法绑定(bind) SVG 属性 r:[attr.r]="...",而不是 [style.r] ="..."

Plunker

关于angularjs - Angular2方法绑定(bind)错误: "value has changed after it was checked",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35710895/

相关文章:

.net - 使用 WriteValue 手动绑定(bind)数据

c# - List<T> 与 BindingList<T> 优点/缺点

JavaScript 组件转换为 TypeScript : What is the type of props

javascript - 使用 SystemJS 加载扩展其他类的类

javascript - 按钮的 Jquery 单击事件在 ng-if div 内不起作用

angularjs - GET 与 POST 在哪里使用哪种方法

javascript - 如何创建仅应用一些过滤器的局部变量?

angularjs - 在加载 AngularJS ap 之前从 AJAX 获取数据

c# - 将字符串数据绑定(bind)到文本框

javascript - 理解柯里化(Currying)函数