当使用材料数据表时,什么可能会导致属性长度为空的异常?

问题描述 投票:0回答:1

我的问题与讨论的问题类似 此处但那里的建议都没有帮助,而我的情况略有不同。

我有一个父组件将一个数组分配给一个子组件的输入属性,然后子组件使用该数据为一个mat表创建一个数据源。我的代码类似于这样。

parent. component. html:

<mat-tab label="Accounts">
  <app-accounts [accounts]="accountOwner?.accounts"></app-accounts>
</mat-tab>

child.component.ts:

@Component({ /// })
  export class AppAccountComponent implements OnInit, OnChanges {
  @Input() accounts: MyAccount[];
tableColumns: string[] = ['name', 'number', 'startDate', 'endDate'];
accountDataSource: MatTableDataSource<MyAccount>;

@ViewChild(MatSort, { static: true }) sort: MatSort;
@ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;

constructor() {
  // tried this as recommended in linked thread, but it had no effect:
  // this.accountDataSource = new MatTableDataSource<MyAccount>();
}

ngOnInit(): void {
  this.sort.active = 'name';
  this.sort.direction = 'asc';
}

ngOnChanges(changes: SimpleChanges): void {
  this.accountDataSource = new MatTableDataSource<MyAccount>(this.accounts);
  this.accountDataSource.sort = this.sort;
  this.accountDataSource.paginator = this.paginator;
}
}

child.component.html:

<table mat-table [dataSource]="accountsDataSource" class="mat-elevation-z1" matSort>
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
    <td mat-cell *matCellDef="let account"> {{account.name}} </td>
  </ng-container>

  <ng-container matColumnDef="number">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Number </th>
    <td mat-cell *matCellDef="let account"> {{account.number}} </td>
  </ng-container>

  <ng-container matColumnDef="startDate">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Effective Date </th>
    <td mat-cell *matCellDef="let account"> {{account.startDate | date:'mediumDate'}} </td>
  </ng-container>

  <ng-container matColumnDef="endDate">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Expiration Date </th>
    <td mat-cell *matCellDef="let account"> {{account.endDate | date:'mediumDate'}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="tableColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: tableColumns;"></tr>
</table>
<mat-paginator [pageSizeOptions]="[5, 10, 20]" [disabled]="!accountsDataSource" [pageSize]="5" showFirstLastButtons>
</mat-paginator>

MyAccounts接口。

export interface MyAccount {
  number: string;
  name: string;
  startDate: Date;
  endDate?: Date;
}

这实际上是正确显示数据的。问题是控制台窗口中的这个异常。

enter image description here

这个 "属性长度为空 "的异常看起来像是来自于 MatTableDataSource._filterData().

angular angular-material
1个回答
0
投票

我想明白了这个问题,但答案却让我很尴尬。

第一次(但不是最后一次)ngOnChanges被命中时,数组是空的,但在随后的几次中就不是了。所以下面的事情就固定下来了。

this.accountDataSource = new MatTableDataSource<MyAccount>(this.accounts ? this.accounts : []);
© www.soinside.com 2019 - 2024. All rights reserved.