表达式在检查后已更改

表达式在检查后已更改

本文介绍了角度4:`ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的子模块中的每个EventEmiiter都会出现此错误,而我找不到针对此问题的修复程序.

Every EventEmiiter in my child module gives this error and I can't find a fix for this.

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'.

这是触发我的EventEmitter的原因:

This is what triggers my EventEmitter:

ngOnChanges(changes: any) {
    if (changes.groupingTabValid) {
        if (changes.groupingTabValid.currentValue !== changes.groupingTabValid.previousValue) {
            this.groupingTabValidChange.emit(this.groupingTabValid);
        }
    }
}

这是我的主要"组件的HTML

Here is my "main" componenent's HTML

<year-overview-grouping [definitionDetails]="definitionDetails"
                        [fixedData]="fixedData"
                        [showValidation]="showValidation"
                        [groupingTabValid]="groupingTabValid"
                        (groupingTabValidChange)="setValidators('groupingTab', $event)">

</year-overview-grouping>

哪个调用此函数

public setValidators(validator: string, e: boolean) {
    switch (validator) {
        case "groupingTab":
            this.groupingTabValid = e;
            break;

        case "selectionTab":
            this.selectionTabValid = e;
            break;
    }

    if (this.groupingTabValid && this.selectionTabValid) {
        this.valid = true;
    } else {
        this.valid = false;
    }
}

1)在一个简单的解释中,是什么导致此错误?

1) In a a simple explanation, what's causing this error?

2)我可以采取什么步骤来解决这个问题?

2) What steps can I take to solve this?

推荐答案

遵守单向数据流规则

尝试使用setTimeout将呼叫延迟发送一秒.

Try to postpone the call to emit for one tick with a setTimeout

if (changes.groupingTabValid.currentValue !== changes.groupingTabValid.previousValue) {
    setTimeout(() => this.groupingTabValidChange.emit(this.groupingTabValid), 0)
}

这篇关于角度4:`ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:02