我需要动态更改我的角度组件中的handontable的高度,但是这样做会在我运行单元测试时引发错误ExpressionChangedAfterItHaHasBeenCheckedError。如何设置高度而不会出现此错误?
我正在用角6和茉莉花。我需要动手操作台的高度进行动态评估,因为我会从父组件中动态添加和删除组件。即使我以相同的方式进行评估,我也没有得到width属性的错误。
<div>
<hot-table
hotId="searchResultsTableId"
[width]="getTableWidth()"
[height]="getTableHeight()"
[data]="data"
>
</hot-table>
</div>
在我组件的打字稿文件中:
getTableHeight(): number {
const style = window.getComputedStyle(this.element, 'height')
const containerHeight = Number(style['height'].split('p')[0])
return containerHeight - 120
}
getTableWidth(): number {
const style = window.getComputedStyle(this.element, 'width')
const containerWidth = Number(style['width'].split('p')[0])
return containerWidth - 50
}
我的规格文件如下:
describe('SearchResultsComponent', () => {
let component: SearchResultsComponent
let fixture: ComponentFixture<SearchResultsComponent>
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [SearchResultsComponent],
imports: [
HotTableModule.forRoot(),
],
providers: [
{ provide: SearchService, useClass: MockSearchService },
]
}).compileComponents()
fixture = TestBed.createComponent(SearchResultsComponent)
component = fixture.debugElement.componentInstance
fixture.detectChanges()
})
describe('processResults', () => {
it('should pass the test', () => {
expect(true).toEqual(true)
})
})
})
运行测试时出现错误“错误:ExpressionChangedAfterItHasBeenCheckedError:表达式已检查后更改。上一个值:'height:-101'。当前值:'height:-43.734399999999994'”,并且仅在以下情况下出现这样绑定到height属性。我希望测试能够通过而不会出现此错误。
答案 0 :(得分:0)
尝试这样的事情:
<div>
<hot-table
hotId="searchResultsTableId"
[width]="tableWidth"
[height]="tableHeight"
[data]="data"
>
</hot-table>
</div>
并在组件的打字稿文件中:
tableHeight: Number;
tableWidth: Number;
ngAfterViewInit() {
this.computeTableHeight();
this.computeTableWidth();
}
computeTableHeight(): number {
const style = window.getComputedStyle(this.element, 'height');
const containerHeight = Number(style['height'].split('p')[0]);
this.tableHeight = containerHeight - 120;
}
computeTableWidth(): number {
const style = window.getComputedStyle(this.element, 'width');
const containerWidth = Number(style['width'].split('p')[0]);
this.tableWidth = containerWidth - 50;
}
说明:Angular不允许在渲染阶段更改属性,因为它会引起某种循环依赖:
AfterViewInit
接口允许在为这种用例设计的特定生命周期挂钩中执行代码。