Angular Material垫表未显示来自数据源的更新数据 [英] Angular Material mat-table is not showing updated data from data source
问题描述
我的简单任务是将输入框中键入的文本添加到垫子表中,但未按预期工作.数据源仅刷新一次,而没有显示第二次更新数据.
My simple task is to add the text typed in an input box to the mat-table but it didn't work as expected. The datasource only refreshed one time and didn't show update data start from the second time.
这是我的代码app.component.html
<div class="main" fxLayout="column" fxGap="10">
<div class="input-area">
<mat-form-field>
<input matInput placeholder="Type something" [(ngModel)]="currentText">
</mat-form-field>
<button mat-raised-button color="primary" style="margin-left:10px;" (click)="onAdd($event)">Add</button>
</div>
<div class="result-area">
<mat-table #table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container matColumnDef="name">
<mat-header-cell #th *matHeaderCellDef> Name </mat-header-cell>
<mat-cell #td *matCellDef="let element"> {{element.name}} </mat-cell>
</ng-container>
<mat-header-row #tr *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row #tr *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
</div>
这是我的"app.component.ts",其中包含用于更新表数据源的添加"事件.
This is my "app.component.ts" which contains "Add" event that updates the table datasource.
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
currentText: string= "";
displayedColumns = ['name'];
data: Data[] = [];
dataSource: Data[];
constructor(){}
onAdd($event){
this.data.push({name: this.currentText});
this.dataSource = this.data;
}
}
interface Data{
name: string;
}
我做错了什么? 这是上面代码
What did I do wrong? Here is the stackblitz example of the above code
推荐答案
对dataSource的引用保持不变,因此资料不知道您的源已更改.
Reference to dataSource remains the same so that material doesn't know that your source changed.
尝试
this.dataSource = [...this.data];
Forked Stackblitz
或使用BehaviorSubject
,例如:
dataSource = new BehaviorSubject([]);
onAdd($event){
this.data.push({name: this.currentText});
console.log(this.data);
this.dataSource.next(this.data);
}
Forked Stackblitz
这篇关于Angular Material垫表未显示来自数据源的更新数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!