【问题标题】:Angular2 binding throws an error "Expression has changed after it was checked"Angular2绑定抛出错误“检查后表达式已更改”
【发布时间】:2017-12-01 09:48:48
【问题描述】:

由于我有如下父子组件,

子组件(RWTaxComponent)

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
    selector: 'rw-tax',
    templateUrl: 'rw.tax.component.html'
})
export class RWTaxComponent implements OnInit {

    @Input() hsn: string = '';
    @Input() srno: string = '';
    @Input() taxPercent: number;
    @Output() taxPercentChange: any = new EventEmitter();
    constructor(
    ) { }

    ngOnInit() {
     }

    ngOnChanges(event) {
        console.log('HSN:: '+this.hsn);
        console.log('SRNO:: '+this.srno);
        if (this.hsn && this.srno) {
            // Doing my logic here to find taxPercent
            this.taxPercentChange.emit(this.taxPercent);
        }
    }}

子组件模板(rw.tax.component.html)是,

<p>{{taxPercent | number:'1.2-2'}}</p>

我在父组件中调用了上面的子组件,如下所示,

<rw-tax [(hsn)]="lineItem.hsn" [(srno)]="lineItem.srno" [(taxPercent)]="lineItem.taxPercent"></rw-tax>

我想在 hsn/srno 改变时改变 taxpercent,这些 hsn/srno 在RWTaxComponent 本身并没有改变,它是由父组件改变的。

所以我使用ngOnChanges() 事件来检测 hsn/srno 已更改,并且每当我更改父组件中的 hsn 和 srno 时都会调用它。 但问题是在按照我的逻辑找到 taxpercent 后,我​​试图通过 this.taxPercentChange.emit(this.taxPercent); 更新父组件中的值并收到错误 “Expression has changed after it was checked”

我是否错误地理解了 Angular2 的生命周期?

请提出正确的方法...

【问题讨论】:

    标签: html angular2-directives angular2-components


    【解决方案1】:

    当组件的输入发生变化时,如果我们试图更改或发出任何属性,就会发生此问题。

    解决方案 1: 尝试承诺解决更改,然后在块中发出输出事件。

    解决方案 2:(可能不起作用) 在发出值时尝试 setTimeout 方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-08
      • 2016-06-13
      • 2017-06-26
      • 2019-01-13
      • 2018-05-11
      • 2017-06-23
      • 2018-06-17
      • 2019-05-14
      相关资源
      最近更新 更多