我正在尝试在 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
将继续递减。因此,您必须编写所有 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] ="..."
。
关于angularjs - Angular2方法绑定(bind)错误: "value has changed after it was checked",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35710895/