>我需要在我的角度组件中动态更改我的可动手的高度,但是当我运行单元测试时,这样做会抛出错误ExpressionChangedAfterItHasBeenCheckedError。如何在不出现此错误的情况下设置高度?
我正在使用角6和茉莉花。我需要动态评估动手表的高度,因为我在父组件中动态添加和删除组件。即使我以相同的方式评估它,我也没有收到宽度属性的错误。
<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)
})
})
})
我收到错误"错误:表达式更改后已检查错误:表达式在检查后已更改。以前的值:"高度:-101"。运行我的测试时,当前值:"高度:-43.734399999999994",这仅在像这样绑定到 height 属性后出现。我希望测试在没有此错误的情况下通过。
尝试这样的事情:
<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 不允许属性在渲染阶段更改,因为它会导致一种循环依赖:
- Angular 正在渲染页面,然后检查动态值
- 动态值取决于呈现的页面
AfterViewInit
接口允许在特定生命周期钩子中执行代码,专为此类用例而设计。