Angular 7:向材料数据表动态添加行

时间:2018-12-15 12:41:31

标签: angular service datatable angular-material

如何将从服务获得的数据动态添加到数据表中?

我从带有AuthenticationService服务的对话框中获取数据。我的第一个想法是使用this.dataSource.push(this.transaction);,这是行不通的。

这是我尝试执行的操作:

export class TransactionPoolComponent implements OnInit {
  displayedColumns = ['sender', 'recipient', 'amount', 'fee'];
  dataSource = ELEMENT_DATA;
  transaction: Transaction;


  constructor(private _AS: AuthenticationService) {
  }

  ngOnInit() {
    this._AS.transaction$.subscribe( transaction => {
      this.transaction = transaction;
      this.dataSource.push(this.transaction);
      console.log(this.transaction);
      }
    );
  }
}

export interface Transaction {
  sender: number;
  recipient: string;
  amount: number;
  fee: string;
}

const ELEMENT_DATA: Transaction[] = [
];

3 个答案:

答案 0 :(得分:2)

如果您看到要添加的数据,这应该可以工作。您需要手动调用 detectChanges 来保持用户界面的更新。您可以使用detectChanges()进行相同操作

您需要在构造函数内部注入

constructor(private ref: ChangeDetectorRef) {

您只需分配数据即可调用

this.dataSource.push(this.transaction);
this.ref.detectChanges(); 

还有一个错误,您需要将元素推入数组,然后将其转换为dataTable,

this.ELEMENT_DATA.push(this.transaction);
this.dataSource = new DataSource(this.ELEMENT_DATA));

答案 1 :(得分:2)

您必须更改数据源引用。

this.dataSource =新的DataSource(新的Array(旧的+新的推送值))

编辑:

Because you don't use **DataSource**, you can do the following
temp = this.datasource.slice();
temp.push(value);
this.datasource = temp;

答案 2 :(得分:0)

您只需要更改数据源的引用,它就会自动检测更改。 类似的东西:

export class TransactionPoolComponent implements OnInit {
  displayedColumns = ['sender', 'recipient', 'amount', 'fee'];
  dataSource = ELEMENT_DATA;
  transaction: Transaction;


  constructor(private _AS: AuthenticationService) {
  }

  ngOnInit() {
    this._AS.transaction$.subscribe( transaction => {
      this.transaction = transaction;
      // You were pushing to dataSource but your data is stored in 'data' 
      // object of dataSource, and you need to changed the reference of the 
      // dataSource by assigning dataSource to itself or assigning a new Array 
      // to dataSource and it would automatically detect the changes and 
      // update the table
      this.dataSource.data = this.dataSource.data.push(this.transaction);
      console.log(this.transaction);
      }
    );
  }
}

export interface Transaction {
  sender: number;
  recipient: string;
  amount: number;
  fee: string;
}

const ELEMENT_DATA: Transaction[] = [
];