角度2:检查后表达式发生了变化

时间:2018-06-07 07:14:11

标签: angular

短篇小说:,当我从我的组件更新变量时收到错误Expression has changed after it was checked. Previous value: 'xx'. Current value: 'xx'.

长篇故事: 我有一个ParentComponent,其中包含我正在更新的名为totalAmount的变量。然后我有ChildComponent影响totalAmount的值,但无法访问所述变量。我的subtotal中有一个ParentComponent变量,我使用ChildComponent传递给@Input然后我只是从{{1}重新计算totalAmount因为我可以访问ParentComponent。就像这样:

subtotal

ParentComponent.ts

然后我将this.totalAmount = this.subtotal + (some other values) 显示在我的ParentComponentTemplate.html上:

<span>{{ totalAmount | money }}</span>

一切正常。然后突然totalAmount必须在input框中,因为应该有一种方法可以覆盖它。因此,我必须这样做,而不是span元素:

<input type="text" name="totalAmount" [(ngModel)]="totalAmount" />

现在就是问题开始的时候。每当subtotal ChildComponent发生变化时,我都会收到错误Expression has changed after it was checked. Previous value: 'xx'. Current value: 'xx'

现在我已经阅读了几篇关于它的文章,它已经是Angular的一个功能,但我们该如何解决这个问题呢?有没有解决方案而不是解决方法?

提前致谢!

2 个答案:

答案 0 :(得分:2)

解决方案是您必须了解错误并相应地更改代码。

虽然非常明确,但此错误并未表明它是生命周期错误

如果你想解决这个问题,你需要遵循生命周期,而不是尝试并看看会发生什么。

虽然你似乎相信你发布了足够的代码,但你没有:下次发布你的整个代码而不是解释,因为即使你觉得很清楚,但对我来说也是如此。

最后,javascript变量通过引用传递:这意味着当您更改输入的值时,您更改引用,而不是值。

那么,你可以尝试一下:

  • 父母的总金额
  • 孩子没有@Input
  • 当子<input>的值发生变化时,您会发出一个事件
  • 父级侦听该事件,并相应地更改总值

答案 1 :(得分:2)

现在问题出现了。每次我的ChildComponent中的小计更改时,我都会在检查后得到错误Expression已更改。之前的价值:&#39; xx&#39;。当前价值:&#39; xx&#39;。

当您在子组件中查找小计时,会出现错误。

您在这里使用了父组件

中的小计
ParentComponent.ts

this.totalAmount = this.subtotal + (some other values)

导致问题。

解决方案可能有助于您执行此类代码

in childcomponent.ts

Promise.resolve(null).then(() => this.parent.subtotal = calculatesubtotal );

看看:Everything you need to know about the ExpressionChangedAfterItHasBeenCheckedError error