ExpressionChangedAfterItHasBeenCheckedError:检查后表达式已更改。以前的值:'undefined'
我知道在*中已经发布了很多相同的问题,并尝试了不同的解决方案来避免运行时错误,但是它们都不适用于我。ExpressionChangedAfterItHasBeenCheckedError:检查后表达式已更改。以前的值:'undefined'
组件和HTML代码
export class TestComponent implements OnInit, AfterContentChecked {
@Input() DataContext: any;
@Input() Position: any;
sampleViewModel: ISampleViewModel = { DataContext: : null, Position: null };
constructor(private validationService: IValidationService, private modalService: NgbModal, private cdRef: ChangeDetectorRef) {
}
ngOnInit() {
}
ngAfterContentChecked() {
debugger;
this.sampleViewModel.DataContext = this.DataContext;
this.sampleViewModel.Position = this.Position;
}
<div class="container-fluid sample-wrapper text-center" [ngClass]="sampleViewModel.DataContext?.Style?.CustomCssClass +' samplewidget-'+ sampleViewModel.Position?.Columns + 'x' + sampleViewModel.Position?.Rows">
//some other html here
</div>
请注意:该组件采用DynamicComponentLoader
后,我的故障排除我已经确定了几个问题动态加载
所有这些子组件的首先是通过使用DynamicComponentResolver并通过输入值像下面
ngAfterViewInit() {
this.renderWidgetInsideWidgetContainer();
}
renderWidgetInsideWidgetContainer() {
let component = this.storeFactory.getWidgetComponent(this.dataSource.ComponentName);
let componentFactory = this._componentFactoryResolver.resolveComponentFactory(component);
let viewContainerRef = this.widgetHost.viewContainerRef;
viewContainerRef.clear();
let componentRef = viewContainerRef.createComponent(componentFactory);
debugger;
(<IDataBind>componentRef.instance).WidgetDataContext = this.dataSource.DataContext;
(<IDataBind>componentRef.instance).WidgetPosition = this.dataSource.Position;
}
即使我改变了我的子组件的HTML像下面我收到此相同error.Just添加一个角度动态加载ngclass属性
<div class="container-fluid ds-iconwidget-wrapper text-center" [ngClass]="Sample">
</div>
我的数据绑定和一切工作都很好。我需要对父组件做任何事情吗? 我已经尝试了子组件中的所有生命周期事件
当子组件/指令的绑定更新已完成时,将触发ngAfterContentChecked
生命周期挂钩。但是您正在更新用作ngClass
指令的绑定输入的属性。那就是问题所在。当Angular运行验证阶段时,它会检测到有属性的挂起更新并引发错误。
理解的错误较好,阅读这两篇文章:
- Everything you need to know about the
ExpressionChangedAfterItHasBeenCheckedError
error - Everything you need to know about change detection in Angular
想想为什么你需要更改ngAfterViewInit
生命周期挂钩的财产。在ngAfterViewInit/Checked
之前触发的任何其他生命周期都可以使用,例如ngOnInit
或ngDoCheck
或ngAfterContentChecked
。
因此要修复它将renderWidgetInsideWidgetContainer
移动到ngOnInit()
生命周期挂钩。
你一定要告诉角度,你更新ngAfterContentChecked 后,可以从导入ChangeDetectorRef @角/核心,并呼吁detectChanges
import {ChangeDetectorRef } from '@angular/core';
constructor(private cdref: ChangeDetectorRef) {}
ngAfterContentChecked() {
debugger;
this.sampleViewModel.DataContext = this.DataContext;
this.sampleViewModel.Position = this.Position;
this.cdref.detectChanges();
}
见我的意见的问题,我已经尝试过这个解决方案,但仍然我得到同样的错误 – JEMI
你怎么加上'TestComponent'的内容? –
@Maximus作为条目组件 – JEMI
@Maximus我试着调用this.cdRef.detectChanges();明确但不起作用 – JEMI