Angular2 方法绑定错误:“检查后值已更改" [英] Angular2 method binding error: "value has changed after it was checked"

查看:22
本文介绍了Angular2 方法绑定错误:“检查后值已更改"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to make a circle board in Angular2. For the example I want to make 10 circles but in reality this number can change. I want to calculate the radius of each circle, so it would be dynamic and not static. See the picture for example

这是我的代码

@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 循环而不是在单独的方法中编写它?

Is there maybe a better way of writing this for loop with *ngFor instead of writing this in a separate method?

推荐答案

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

In development mode (the default), change detection is run twice to ensure that model changes have stabilized. This means that the ngFor loop is evaluated twice. Hence property x will continue to be decremented the second time change detection runs. Other activity in your app will also cause change detection to run, and x will continue to be decremented. Therefore, you must write all view functions, like calculateRadius(), assuming they will be executed many times. E.g.:

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

模板语法开发指南在描述时提到了这一点幂等表达式.

The Template Syntax dev guide mentions this when it describes idempotent expressions.

这样也可以解决检查后值发生变化的问题.

This will also solve the value has changed after it was checked problem.

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

You also need to bind SVG attribute r using this syntax: [attr.r]="...", not [style.r]="...".

Plunker

这篇关于Angular2 方法绑定错误:“检查后值已更改"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆