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.
Here is my code 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>
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
Instead of push use concat to let table know that you modified the object
this.data = this.data.concat([{name: this.currentText}]);
Reference to dataSource remains the same so that material doesn't know that your source changed.
Try
this.dataSource = [...this.data];
Forked Stackblitz
Or use BehaviorSubject
like:
dataSource = new BehaviorSubject([]);
onAdd($event){
this.data.push({name: this.currentText});
console.log(this.data);
this.dataSource.next(this.data);
}
Forked Stackblitz
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With