首页 > 解决方案 > 如何用 MatGridList 实现动态列?

问题描述

我有一个显示数据数组的 Mat-G​​rid-List。我想让cols属性是动态的。cols 的数量取决于我的盒子的大小。我已将代码放入stackblitz。当框被调整大小时,它还应该重新计算列。此时出现以下错误,该函数仅被调用一次:

错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。以前的值:'cols:2'。当前值:“列:6”。

标签: angulartypescriptangular-materialgrid

解决方案


You don't need to use the setter ViewChild at all. Just create a simple function called setColumns which updates the columns in the HTML. Use the window:resize event in the HTML to call this function and also call it in ngOnInit to make it resize on load.

@ViewChild('box', {static: true}) box: ElementRef;

ngOnInit() {
    this.setColumns();
}

setColumns() {
    this.columns = Math.floor(this.box.nativeElement.clientWidth / 100);
}

In the template, just call setColumns on window:resize.

<mat-grid-list [cols]="columns" (window:resize)="setColumns()" rowHeight="100px" width="100%">

Here is a working example on StackBlitz.


推荐阅读