Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

like image 600
Sithu Kyaw Avatar asked Jun 14 '18 03:06

Sithu Kyaw


Video Answer


2 Answers

Instead of push use concat to let table know that you modified the object

   this.data = this.data.concat([{name: this.currentText}]);
like image 79
Vova Bilyachat Avatar answered Oct 01 '22 08:10

Vova Bilyachat


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

like image 31
yurzui Avatar answered Oct 01 '22 08:10

yurzui