首页 > 解决方案 > 错误设置宽度 - 错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改

问题描述

我使用 akendo-grid来显示一些数据。我使用[width]属性动态地将所需的宽度应用于每一列。我有一个columnsWidths: Array<{ field: string, width: number }>要达到的结果。

html

<kendo-grid-column field="Title" title="{{lbl_ColTitle}}" [hidden]="isHidden('Title')" [width]="isWidth('Title')" class="editableGridCell" [editable]="!APsService.isLoading && isPendingDocument && isGDPRApproved && !isTemplate && isAllowedToUpdate">
     <ng-template kendoGridCellTemplate let-dataItem>
         {{dataItem.Title}}
     </ng-template>
</kendo-grid-column>
<kendo-grid-column field="Description" title="{{lbl_ColDescription}}" [hidden]="isHidden('Description')" [width]="isWidth('Description')" class="editableGridCell" [editable]="!APsService.isLoading && isPendingDocument && isGDPRApproved && !isTemplate && isAllowedToUpdate">
     <ng-template kendoGridCellTemplate let-dataItem>
         {{dataItem.Description}}
     </ng-template>
</kendo-grid-column>

ts

public isWidth(columnName: string): number {
    return this.columnsWidths.findIndex((item: any) => item.field === columnName) > -1 && this.columnsWidths.filter((item: any) => item.field === columnName)[0].width;   
}

使用上面的代码,一切看起来都很棒。但是,我想在特定情况下稍微修改宽度(当列的宽度大于可用的网格宽度时)。因此,我将代码更改为:

public isWidth(columnName: string): number {
    if (this.columnsWidths.filter((item: any) => item.width >= this.gridView.wrapper.nativeElement.offsetWidth).length > 0) {         
        return this.columnsWidths.findIndex((item: any) => item.field === columnName) > -1 && this.columnsWidths.filter((item: any) => item.field === columnName)[0].width * 0.7;
    }
    else {
        return this.columnsWidths.findIndex((item: any) => item.field === columnName) > -1 && this.columnsWidths.filter((item: any) => item.field === columnName)[0].width;
    }
}

显示的实际结果是正确的(列宽似乎已正确应用),但我的控制台中出现以下错误:

ERROR 错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。以前的值:'宽度:641.1999999999999'。当前值:'宽度:916'。

我确实试图console.log找出isWidth方法中发生了什么,并发现最初满足第一个条件(它不应该因为保存的设置{field: "Description", width: 916}gridView.wrapper.nativeElement.offsetWidth1830),之后,第二个条件不断满足(正如预期的那样)。

我怎样才能避免这个错误?谢谢你。

标签: angularkendo-gridangular7kendo-ui-angular2

解决方案


我试图找到一个解决方案,从许多来源阅读很多东西。尝试了几种解决方法,我发现我的解决方案如下:

ngAfterViewInit() {
    this.ref.detectChanges(); <--- this is the only code I added 
    setTimeout(() => {
        this.calcPageSize();
    });
    window.addEventListener('resize', this.calcPageSizeOnResize);
}

但是,使用concole.log我意识到它的行为方式相同。最初满足第一个条件,然后在组件的剩余生命周期中满足第二个条件。不同之处在于错误从我的控制台输出中消失了。

我希望这种添加不会产生不良影响,并且不会以不希望的方式发生其他任何变化。

这对我帮助很大https://stackoverflow.com/a/52922389/9880356在这里您可以找到一个非常有用的来源:https ://medium.com/angular-in-depth/everything-you-need-to-知道表达式在检查后更改错误-错误-e3fd9ce7dbb4


推荐阅读