Angular Material mat-table未显示数据源中的更新数据

Sit*_*yaw 4 angular-material angular

我的简单任务是将输入框中输入的文本添加到mat-table,但它没有按预期工作.数据源仅刷新一次,并且未显示第二次更新数据.

这是我的代码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>
Run Code Online (Sandbox Code Playgroud)

这是我的"app.component.ts",其中包含更新表数据源的"添加"事件.

@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;
}
Run Code Online (Sandbox Code Playgroud)

我做错了什么?这是上面代码的stackblitz示例

谢谢你的帮助.

yur*_*zui 17

对dataSource的引用保持不变,因此材料不知道您的源更改.

尝试

this.dataSource = [...this.data];
Run Code Online (Sandbox Code Playgroud)

分叉Stackblitz

或使用BehaviorSubject如下:

dataSource = new BehaviorSubject([]);

onAdd($event){
  this.data.push({name: this.currentText});
  console.log(this.data);
  this.dataSource.next(this.data);
}
Run Code Online (Sandbox Code Playgroud)

分叉Stackblitz

  • 顺便说一句,您可以通过this.dataSource.next([... .... this.dataSource.getValue,... [{name:this.currentText}]])进行改进; (2认同)
  • @Volodymyr Bilyachat很高兴知道你知道如何改进它.我刚刚表现出正确的方向 (2认同)

Vol*_*hat 7

而不是使用concat来让表知道您已修改了对象,

   this.data = this.data.concat([{name: this.currentText}]);
Run Code Online (Sandbox Code Playgroud)