首页 > 解决方案 > 在观察者中调用 Angular detectChanges() 会导致视图更新带有过时的标记参数

问题描述

我的模板中有一些动态内联样式,它们决定了表单中某些元素的大小。喜欢:

[style.maxWidth.px]='firstInput.nativeElement.offsetWidth'

问题是,在 AfterViewInit 生命周期挂钩中,我调用 detectChanges() 方法来更新视图,然后我看到我的表单具有动态设置的适当字段大小,但是当检索到来自该表单的后端数据时,我再次调用 detectChanges()关闭加载器,当未计算字段大小时,我的表单将回滚到初始状态。

之后导致更改检测的任何更改都会使模板再次重新计算大小。

例子:

ngAfterViewInit() {
        this.loadData();
        this.detector.detectChanges();
    } 
private loadData(): void {
        this.loading(true);
        this.detector.markForCheck();
        this.service.getSomeData()
            .subscribe(
                res => {
                    this.loading(false);
                    this.detector.detectChanges(); // this is where view update is not what I expect
                },
                err => {
                    this.loading(false);
                    this.processLoadingError(err);
                    this.detector.detectChanges();
                });
    }

为什么观察者内部的 detectChanges() 行为如此?我可以做些什么来获得我想要的东西(使用计算的样式更新视图并在收到数据后再次更新以关闭加载器而不更改我已经获得的正确样式)。

谢谢!

标签: angularangular2-changedetection

解决方案


推荐阅读