数据源数组中的数据更改后,如何使Angular mat-table自动刷新

时间:2019-11-12 22:43:48

标签: angular angular-material mat-table

我有一个带垫台的Angular v8材质设计应用程序。它的数据源是一个简单的数组。 我添加,删除和修改了数组中的项目,我希望mat-table能够显示更改,而无需用户刷新。 (这特别糟糕,因为当使用Angular页面时,F5刷新会使您找不到页面)。

我已经对此进行了大量搜索,而我最喜欢的文章是: Angular + Material - How to refresh a data source (mat-table) 它有21个,是的21个建议答案。我一定会丢失一些东西,但是我会认为mat-table的设计者会提供一个简单的简单javascript调用来实现这一目标。 虽然我希望得到任何人的一个很好的答案,但我特别希望Angular团队的工程师解释他们如何认为应该使用表来提供动态的自动绑定,类似于如何从html绑定简单的变量。到javascripot,例如:  {{personName}}

谢谢

================================================ ================

代码


import { Component, OnInit } from '@angular/core';
import { Element } from '../Element';
import { ElementsService } from '../elements.service';
import { MatTable} from '@angular/material';

export interface PeriodicElement {
  _id: string;
  name: string;
  weight: number;
  symbol: string;
}

@Component({
  selector: 'app-table-to-mongo',
  templateUrl: './table-to-mongo.component.html',
  styleUrls: ['./table-to-mongo.component.css']
})
export class TableToMongoComponent implements OnInit {

 // this is the real array that the table displays from, I load it from a call to mongo
  PeriodicElement: Element[] = [];

  // needed for mat-table

  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = this.PeriodicElement;

=========================

able starts here -->
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

    <!--- Note that these columns can be defined in any order.
          The actual rendered columns are set as a property on the row definition" -->

    <!-- Position Column -->
    <!-- shows as position but it linked to my _id property -->
    <ng-container matColumnDef="position">
      <th mat-header-cell *matHeaderCellDef> No. </th>
      <td mat-cell *matCellDef="let element"> {{element._id}} </td>
    </ng-container>


    <!-- Name Column -->
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef> Name </th>
      <td mat-cell *matCellDef="let element"> {{element.name}} </td>
    </ng-container>

    <!-- Weight Column -->
    <ng-container matColumnDef="weight">
      <th mat-header-cell *matHeaderCellDef> Weight </th>
      <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
    </ng-container>

    <!-- Symbol Column -->
    <ng-container matColumnDef="symbol">
      <th mat-header-cell *matHeaderCellDef> Symbol </th>
      <td mat-cell *matCellDef="let element"> {{element.symbol}} </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>

    <!-- this line is what gets me the "click on any row and give me a row object" functionality -->
    <tr mat-row *matRowDef="let row; columns: displayedColumns;" (click)="selectRow(row)"></tr>

  </table>    

0 个答案:

没有答案