Angular2方法绑定错误:"它检查&QUOT后的值发生变化的; [英] Angular2 method binding error: "value has changed after it was checked"

查看:207
本文介绍了Angular2方法绑定错误:"它检查&QUOT后的值发生变化的;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想作一圆板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

这是我的code

@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;
    }
}

不过,我得到以下错误:

But I get the following error:

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 ,而不是一个单独的方法写这个?

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;
}

的模板语法开发指南中提到了这一点描述幂等前pressions 的。

这也将解决它检查后值更改的问题。

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

您还需要绑定SVG属性研究使用此语法: [attr.r] =...,不是 [style.r] =...

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

<大骨节病> Plunker

这篇关于Angular2方法绑定错误:&QUOT;它检查&QUOT后的值发生变化的;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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