因@Input变量更新出现"Expression has changed after it was checked."如何解决?
How to solve "Expression has changed after it was checked." when occuring because of the @Input variable update?
当网页容器滚动时,我使用将目标发送到 parent 元素的事件发射器。 parent 页面发送到另一个 child - 菜单 - 目标,以便菜单可以相应地激活/停用菜单标题。变量可以从容器发送和更新到 parent,但是当从 parent 进一步发送到 child(菜单组件)时,错误
ERROR Error: "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'Home: undefined'. Current value: 'Home: true'."
更新parent:
<scroll-card (id_active) ="activate_id($event)"></scroll-card>
和组件
export class Parent implements OnInit {
home:boolean;
constructor() {}
ngOnInit() {}
activate_id(message: string){
if(message == "Home"){
this.home=true;
}
}
}
这就是我将数据发送到 child 的方式:
<menu [Home] ="home"></menu>
这就是我接收数据的方式:
import { Component, OnInit, Input, EventEmitter, SimpleChanges } from '@angular/core';
@Component({
selector: 'menu',
templateUrl: 'menu',
styleUrls: ['./menu.component.scss']
export class Menu implements OnInit {
constructor() { }
ngOnInit() {
}
@Input() Home;
}
为了真正理解为什么会发生这种情况,您需要展示如何向 id_active
发出更改。但是,始终可以手动触发更改检测:
import { ChangeDetectorRef } from '@angular/core';
export class Parent implements OnInit {
home:boolean;
constructor(private cdRef:ChangeDetectorRef) {}
ngOnInit() {}
activate_id(message: string){
if(message == "Home"){
this.home=true;
this.cdRef.detectChanges();
}
}
}
当网页容器滚动时,我使用将目标发送到 parent 元素的事件发射器。 parent 页面发送到另一个 child - 菜单 - 目标,以便菜单可以相应地激活/停用菜单标题。变量可以从容器发送和更新到 parent,但是当从 parent 进一步发送到 child(菜单组件)时,错误
ERROR Error: "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'Home: undefined'. Current value: 'Home: true'."
更新parent:
<scroll-card (id_active) ="activate_id($event)"></scroll-card>
和组件
export class Parent implements OnInit {
home:boolean;
constructor() {}
ngOnInit() {}
activate_id(message: string){
if(message == "Home"){
this.home=true;
}
}
}
这就是我将数据发送到 child 的方式:
<menu [Home] ="home"></menu>
这就是我接收数据的方式:
import { Component, OnInit, Input, EventEmitter, SimpleChanges } from '@angular/core';
@Component({
selector: 'menu',
templateUrl: 'menu',
styleUrls: ['./menu.component.scss']
export class Menu implements OnInit {
constructor() { }
ngOnInit() {
}
@Input() Home;
}
为了真正理解为什么会发生这种情况,您需要展示如何向 id_active
发出更改。但是,始终可以手动触发更改检测:
import { ChangeDetectorRef } from '@angular/core';
export class Parent implements OnInit {
home:boolean;
constructor(private cdRef:ChangeDetectorRef) {}
ngOnInit() {}
activate_id(message: string){
if(message == "Home"){
this.home=true;
this.cdRef.detectChanges();
}
}
}