我正在开发一个 Angular 7.3.8 应用程序,我正在使用 Angular Material 库。我可以mat-table
通过 NgOnInit 循环用数据初始化组件,但是当我尝试通过某些函数用一些数据更新表时,UI 没有被更新。
已经尝试使用 NgZone 强制更新 UI,但仍然无法正常工作。
这是模板的代码:
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<!-- Checkbox Column -->
<ng-container matColumnDef="select">
<th mat-header-cell *matHeaderCellDef>
<mat-checkbox (change)="$event ? masterToggle() : null"
[checked]="selection.hasValue() && isAllSelected()"
[indeterminate]="selection.hasValue() && !isAllSelected()"
>
</mat-checkbox>
</th>
<td mat-cell *matCellDef="let row">
<mat-checkbox (click)="$event.stopPropagation()"
(change)="$event ? selection.toggle(row) : null"
[checked]="selection.isSelected(row)"
>
</mat-checkbox>
</td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="day">
<th mat-header-cell *matHeaderCellDef> Day </th>
<td mat-cell *matCellDef="let element"> {{element.day | titlecase}} </td>
</ng-container>
<!-- Weight Column -->
<ng-container matColumnDef="startHour">
<th mat-header-cell *matHeaderCellDef> Start Hour </th>
<td mat-cell *matCellDef="let element"> {{element.startHour}} </td>
</ng-container>
<!-- Symbol Column -->
<ng-container matColumnDef="endHour">
<th mat-header-cell *matHeaderCellDef> End Hour </th>
<td mat-cell *matCellDef="let element"> {{element.endHour}} </td>
</ng-container>
<ng-container matColumnDef="action">
<th mat-header-cell *matHeaderCellDef> Action </th>
<td mat-cell *matCellDef="let element"> {{element.action}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"
(click)="selection.toggle(row)">
</tr>
</table>
这是更新功能:
ngOnInit(){
this.dataSource = [
{ day: 'Monday' , startHour: '9: 00 am', endHour: '13:00 pm',
action: '' };
}
addPeriod(form: any){
const obj = {
day: form.value.pickedDay,
startHour: form.value.startHour + ': 00 am',
endHour: form.value.endHour + ': 00 pm',
action: ''
} as TableSchedule;
this.zone.run(() => {
this.dataSource.push(obj);
console.log('new data:', this.dataSource);
});
}
日志显示 dataSource 数组正在更新,但 UI 未显示新值。