ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。先前值:“未定义”

2024-06-19

我知道堆栈溢出中已经发布了很多相同的问题,并尝试了不同的解决方案来避免运行时错误,但它们都不适合我。

组件和 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,我也会遇到同样的错误。只需添加一个 Angular ngclass 属性

<div class="container-fluid ds-iconwidget-wrapper text-center" [ngClass]="Sample">

</div>

我的数据绑定和一切工作正常。我需要对父组件执行任何操作吗? 我已经尝试了子组件中的所有生命周期事件


你必须告诉angular您之后更新了内容ngAfterContentChecked你可以导入ChangeDetectorRef from @angular/core并打电话detectChanges

import { ChangeDetectorRef } from '@angular/core';

constructor( private cdref: ChangeDetectorRef ) {}   

ngAfterContentChecked() {
    this.sampleViewModel.DataContext = this.DataContext;
    this.sampleViewModel.Position = this.Position;
    this.cdref.detectChanges();
 }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。先前值:“未定义” 的相关文章

随机推荐