如何使Mat-G​​rid-List列属性动态化?

时间:2019-09-26 05:26:24

标签: html angular typescript angular-material

我想要一个Mat-G​​rid-List,可以在其中动态更改在框的宽度上确定的“ cols”属性的数量,如下所示:

<mat-grid-list [cols]="getAttachmentColumns()" rowHeight="100px" style="width: 100%;">
  <mat-grid-tile *ngFor="let attachment of attachments; let i = index">
    ...
  </mat-grid-tile>
</mat-grid-list>
@ViewChild('attachments', {static: false}) attachments: ElementRef;
getAttachmentColumns(): number {
  if(this.attachments) {
    let n = Math.floor(this.attachments.nativeElement.clientWidth / 100);
    return (n > 0 ? n : 1);
  } else {
    return 1;
  }
}

使用此代码,我总是收到以下警告/错误:

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'cols: 1'. Current value: 'cols: 5'.
    at viewDebugError (core.js:25491)
    at expressionChangedAfterItHasBeenCheckedError (core.js:25468)
    at checkBindingNoChanges (core.js:25772)
    at checkNoChangesNodeInline (core.js:38548)
    at checkNoChangesNode (core.js:38521)
    at debugCheckNoChangesNode (core.js:39482)
    at debugCheckDirectivesFn (core.js:39379)
    at Object.eval [as updateDirectives] (TicketDetailControlComponent.html:296)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:39364)
    at checkNoChangesView (core.js:38354)

1 个答案:

答案 0 :(得分:0)

首次导入ChangeDetectorRef:

import { ChangeDetectorRef } from '@angular/core';

然后实现如下所示的ngAfterViewChecked函数。

constructor(private changeDetectorRef : ChangeDetectorRef){}

ngAfterViewChecked(){
  this.changeDetectorRef.detectChanges();
}

这对我有用。