I'm experiencing a similar issue as the one discussed in this post, but none of the suggestions there have resolved my problem, and my scenario has some differences.
In my case, a parent component is assigning an array to a child component's input property, which is then used to create a data source for a mat table. Here is a snippet of my code:
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 the recommended approach from the linked thread, to no avail:
// 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>
The structure of the MyAccounts interface is as follows:
export interface MyAccount {
number: string;
name: string;
startDate: Date;
endDate?: Date;
}
The data is being displayed correctly, however, I am encountering a "property length of null" exception in the console window, which seems to be originating from MatTableDataSource._filterData()
.