A
A
Alena Khrenovskaya2018-05-14 16:22:16
JavaScript
Alena Khrenovskaya, 2018-05-14 16:22:16

Angular material table and DataSource?

Good afternoon! How can I connect a ready-made array obtained from the database to mat-table?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Stroykin, 2018-05-14
@ally69

Let's say we have a home.service.ts service through which our array comes to us

public getElementData(): Observable<any[]> {
  return this._httpClient.get('api/test'); // any[]
}

We take the HTML code from the example from the link
In the home.component.ts component, we declare 2 properties and 1 method that is called in OnInit
public displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
public dataSource;

// constructor ...

ngOnInit(): void {
  this._getElementData();
}

private _getElementData(): void {
  this._homeService.getElementData().subscribe(res => {
    this.dataSource = new MatTableDataSource(res);
  });
}

or
public displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
public dataSource = new MatTableDataSource();

// constructor ...

ngOnInit(): void {
  this._getElementData();
}

private _getElementData(): void {
  this._homeService.getElementData().subscribe(res => {
    this.dataSource.data = res;
  });
}

We end up with this picture:
Well, a link with a good, comprehensive, example (Angular 5.2 and rxjs 5.5) - stackblitz

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question