【问题标题】:Angular Material mat-table is not showing updated data from data sourceAngular Material mat-table 未显示来自数据源的更新数据
【发布时间】:2018-06-14 03:08:26
【问题描述】:

我的简单任务是将在输入框中键入的文本添加到 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>

这是我的“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;
}

我做错了什么? 这里是上面code的stackblitz例子@

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

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

    试试

    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

    【讨论】:

    • 顺便说一句,你可以通过 this.dataSource.next([ ...this.dataSource.getValue, ...[{name: this.currentText}]]);
    • 很高兴知道这一点
    • @Volodymyr Bilyachat 很高兴知道您知道如何改进它。我刚刚指出了正确的方向
    【解决方案2】:

    使用 concat 代替 push 让 table 知道你修改了对象

       this.data = this.data.concat([{name: this.currentText}]);
    

    【讨论】:

    • 为什么有人减去这个?那个人理解 push 和 concat 之间的区别吗?:)
    • @Alexandre 没有什么奇怪的角度会通过引用比较数据
    【解决方案3】:

    愿你能用新数据重建表。

    this.tableData = this.dataSource.data;
    this.dataSource.data = this.tableData.push(newRecord);
    this.dataSource = new MatTableDataSource<any>(this.tableData);
    

    【讨论】:

      【解决方案4】:

      只需隐藏表格,直到数据显示然后显示。简单但有效。我为此使用 *ngIf="..." 和 Angular。

      【讨论】:

        猜你喜欢
        • 2020-12-18
        • 2018-03-26
        • 2019-06-03
        • 1970-01-01
        • 2021-07-08
        • 2019-07-01
        • 2020-02-01
        • 1970-01-01
        • 2019-02-14
        相关资源
        最近更新 更多