【问题标题】:Angular - ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checkedAngular - ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改
【发布时间】:2021-09-15 16:01:51
【问题描述】:

我真的无法理解,我已经尝试在谷歌搜索,这里,任何地方......我不明白为什么这个错误仍然显示。

我有这样的事情:

parent.html

<child-1 [(type)]="type"></child-1>

parent.ts

type = 0;
getTypeToOtherthings() { // function to use in a mouse event, it's not important for that
    console.log(type);
}

child-1.html

<child-2 [(type)]="type">

child-1.ts // 这个组件就像是 parent 和 child-2 之间的桥梁(可能问题出在这里,我真的不知道)

_type: number;
@Input() set type(val: number) {
  this.typeChange.emit(val);
  this._type= val;
}
get type() {
  return this._type;
}
@Output() typeChange: EventEmitter<number> = new EventEmitter<number>();

child-2.html

(一些 HTML)

child-2.ts

_type: number;
@Input() set type(val: number) {
  this.typeChange.emit(val);
  this._type= val;
}
get type() {
  return this._type;
}
@Output() typeChange: EventEmitter<number> = new EventEmitter<number>();

/*I need change Type variable in childs-2, so i put this in 
onInit (but i already tryed put this in all Afters... , using Promise, ChangeDetectorRef, nothing works,
like everything works fine but the error still)*/
ngOnInit() {
    this.type = 2;
}

毕竟我几乎要放弃了

【问题讨论】:

  • 您实际上并没有发布错误消息,第一行可能就足够了。并且在从parent传到child 1和从child 1传到child 2时临时重命名type,这样调试就更容易了。

标签: angular typescript


【解决方案1】:

又快又脏,但是如果你看到这个问题并且知道问题所在,你可以在 setTimout 中运行它,例如

setTimeout(()=> this.markersEventsType = 2;)

但可能有更合适的解决方案。在构造函数中设置 eventType 不起作用吗?如果您从服务中获取更改,您是否尝试过使用异步管道?

【讨论】:

    【解决方案2】:

    这表明您的应用存在问题。 简而言之,您正在修改模型而不是视图。 Angular 的 devMode 除了已经存在的检查外,还添加了更新检查。这些检查会查找模型中的任何更新,以便更新视图。

    您收到此错误是因为这些检查都无法检测到模型中的更改。因此,一种解决方案是使用ChangeDetectorRef。调用 detectChanges() 会告诉您的应用模型中的某些内容发生了变化,并且可以更新 vue。

    除了这个答案之外,我强烈建议您查看change detection strategies,我认为这会使代码更易于理解(因为它会强制您使用 ChangeDetection),并且以更一般的方式,您的应用程序会运行得更流畅。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-19
      • 1970-01-01
      • 2018-10-23
      • 2019-05-14
      • 2018-11-06
      • 2019-02-19
      • 2018-04-22
      • 1970-01-01
      相关资源
      最近更新 更多