Home > Software engineering >  Show Json data into <Mat-Table> in angular component
Show Json data into <Mat-Table> in angular component

Time:09-09

I'm fetching the records from database using Laravel-api. I successfully show the data into console.log(). But unable to show it to <mat-table> element of Angular Materials.

There is some default information showing inside the mat-table. I want to change it to dynamic users data.

Component.ts

import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';


export interface PeriodicElement {
  name: string;
  email: string;
  position: number;
}
const ELEMENT_DATA: PeriodicElement[] = [
  
  {position: 1, name: 'Hydrogen', email: '1.0079'},
  {position: 13, name: 'Aluminum', email: '26.9815'},
  {position: 14, name: 'Silicon', email: '28.0855'},
  {position: 15, name: 'Phosphorus', email: '30.9738'},
  {position: 16, name: 'Sulfur', email: '32.065'},
  {position: 17, name: 'Chlorine', email: '35.453'},
  {position: 18, name: 'Argon', email: '39.948'},
  {position: 19, name: 'Potassium', email: '39.0983'},
  {position: 20, name: 'Calcium', email: '40.078'},
];

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss']
})

export class DashboardComponent implements OnInit, AfterViewInit {

  users:any;
  displayedColumns: string[] = ['position', 'name', 'email'];
  dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);


  constructor() { }

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

  getUsersData() {
    this.dataService.getData().subscribe(res => {
      this.users = res;
      console.log(res);
    });
  }

}

My View

<table mat-table [dataSource]="dataSource">

  <!-- Position Column -->
  <ng-container matColumnDef="position">
    <th mat-header-cell *matHeaderCellDef> No. </th>
    <td mat-cell *matCellDef="let element"> {{element.position}} </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="email">
    <th mat-header-cell *matHeaderCellDef> Email </th>
    <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
  </ng-container>


  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

The Dataservice.ts file

import { Injectable } from '@angular/core';

import { HttpClient } from '@angular/common/http';

import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor(private http:HttpClient) { }

 

  getData() {
    return this.http.get(environment.apiUrl '/users/');
  }

}

The data I'm getting in the console.log(res).

0
: 
{id: 1, name: 'Marlen Green', email: '[email protected]', created_at: '2022-09-07T07:09:55.000000Z', updated_at: '2022-09-07T07:09:55.000000Z'}
1
: 
{id: 2, name: 'Buck Gaylord I', email: '[email protected]', created_at: '2022-09-07T07:09:55.000000Z', updated_at: '2022-09-07T07:09:55.000000Z'}
2
: 
{id: 3, name: 'Orlando Trantow', email: '[email protected]', created_at: '2022-09-07T07:09:55.000000Z', updated_at: '2022-09-07T07:09:55.000000Z'}
3
: 
{id: 4, name: 'Jewell Gibson', email: '[email protected]', created_at: '2022-09-07T07:09:55.000000Z', updated_at: '2022-09-07T07:09:55.000000Z'}
4
: 
{id: 5, name: 'Ramiro Schamberger', email: '[email protected]', created_at: '2022-09-07T07:09:55.000000Z', updated_at: '2022-09-07T07:09:55.000000Z'}
5
: 
{id: 6, name: 'Miss Maudie Steuber III', email: '[email protected]', created_at: '2022-09-07T07:09:56.000000Z', updated_at: '2022-09-07T07:09:56.000000Z'}
6
: 
{id: 7, name: 'Allen Bruen', email: '[email protected]', created_at: '2022-09-07T07:09:56.000000Z', updated_at: '2022-09-07T07:09:56.000000Z'}
7
: 
{id: 8, name: "Efren O'Kon", email: '[email protected]', created_at: '2022-09-07T07:09:56.000000Z', updated_at: '2022-09-07T07:09:56.000000Z'}
8
: 
{id: 9, name: 'Mrs. Carolyn Lowe', email: '[email protected]', created_at: '2022-09-07T07:09:56.000000Z', updated_at: '2022-09-07T07:09:56.000000Z'}
9
: 
{id: 25, name: 'Muhammad Shahzaib', email: '[email protected]', created_at: '2022-09-08T05:46:19.000000Z', updated_at: '2022-09-08T05:46:19.000000Z'}
10
: 
{id: 26, name: 'Muhammad Shahzaib', email: '[email protected]', created_at: '2022-09-08T05:52:50.000000Z', updated_at: '2022-09-08T05:52:50.000000Z'}
11
: 
{id: 27, name: 'Muhammad Shahzaib', email: '[email protected]', created_at: '2022-09-08T05:53:50.000000Z', updated_at: '2022-09-08T05:53:50.000000Z'}

How can I show data from function getUsersdata() into this table.

CodePudding user response:

Please check my below example, after making the api call, you can reinitialize using the same way you initialize.

ts

import { Component } from '@angular/core';
import { MatTableDataSource } from '@angular/material';
import { DataService } from './data.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular 5';
  displayedColumns = ['position', 'name', 'weight', 'symbol'];
  dataSource = new MatTableDataSource<Element>([]);

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.getUsersData();
  }

  getUsersData() {
    this.dataService.getData().subscribe((res) => {
      this.dataSource = new MatTableDataSource<Element>(res);
    });
  }
}

export interface Element {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}

html

<hello name="{{ name }}"></hello>
<p>Start editing to see some magic happen :)</p>

<div >
  <mat-table #table [dataSource]="dataSource">
    <!--- 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 -->
    <ng-container matColumnDef="position">
      <mat-header-cell *matHeaderCellDef> ID </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{ element.id }} </mat-cell>
    </ng-container>

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

    <!-- Email Column -->
    <ng-container matColumnDef="email">
      <mat-header-cell *matHeaderCellDef> Email </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{ element.email }} </mat-cell>
    </ng-container>

    <!-- Weight Column -->
    <ng-container matColumnDef="weight">
      <mat-header-cell *matHeaderCellDef> Created At </mat-header-cell>
      <mat-cell *matCellDef="let element">
        {{ element.created_at | date }}
      </mat-cell>
    </ng-container>

    <!-- Symbol Column -->
    <ng-container matColumnDef="symbol">
      <mat-header-cell *matHeaderCellDef> Updated At </mat-header-cell>
      <mat-cell *matCellDef="let element">
        {{ element.updated_at | date }}
      </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
  </mat-table>
</div>

data.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { of } from 'rxjs/observable/of';
import { delay } from 'rxjs/operators';

@Injectable()
export class DataService {
  data = [
    {
      id: 1,
      name: 'Marlen Green',
      email: '[email protected]',
      created_at: '2022-09-07T07:09:55.000000Z',
      updated_at: '2022-09-07T07:09:55.000000Z',
    },
    {
      id: 2,
      name: 'Buck Gaylord I',
      email: '[email protected]',
      created_at: '2022-09-07T07:09:55.000000Z',
      updated_at: '2022-09-07T07:09:55.000000Z',
    },
    {
      id: 3,
      name: 'Orlando Trantow',
      email: '[email protected]',
      created_at: '2022-09-07T07:09:55.000000Z',
      updated_at: '2022-09-07T07:09:55.000000Z',
    },
    {
      id: 4,
      name: 'Jewell Gibson',
      email: '[email protected]',
      created_at: '2022-09-07T07:09:55.000000Z',
      updated_at: '2022-09-07T07:09:55.000000Z',
    },
    {
      id: 5,
      name: 'Ramiro Schamberger',
      email: '[email protected]',
      created_at: '2022-09-07T07:09:55.000000Z',
      updated_at: '2022-09-07T07:09:55.000000Z',
    },
    {
      id: 6,
      name: 'Miss Maudie Steuber III',
      email: '[email protected]',
      created_at: '2022-09-07T07:09:56.000000Z',
      updated_at: '2022-09-07T07:09:56.000000Z',
    },
    {
      id: 7,
      name: 'Allen Bruen',
      email: '[email protected]',
      created_at: '2022-09-07T07:09:56.000000Z',
      updated_at: '2022-09-07T07:09:56.000000Z',
    },
    {
      id: 8,
      name: "Efren O'Kon",
      email: '[email protected]',
      created_at: '2022-09-07T07:09:56.000000Z',
      updated_at: '2022-09-07T07:09:56.000000Z',
    },
    {
      id: 9,
      name: 'Mrs. Carolyn Lowe',
      email: '[email protected]',
      created_at: '2022-09-07T07:09:56.000000Z',
      updated_at: '2022-09-07T07:09:56.000000Z',
    },
    {
      id: 25,
      name: 'Muhammad Shahzaib',
      email: '[email protected]',
      created_at: '2022-09-08T05:46:19.000000Z',
      updated_at: '2022-09-08T05:46:19.000000Z',
    },
    {
      id: 26,
      name: 'Muhammad Shahzaib',
      email: '[email protected]',
      created_at: '2022-09-08T05:52:50.000000Z',
      updated_at: '2022-09-08T05:52:50.000000Z',
    },
    {
      id: 27,
      name: 'Muhammad Shahzaib',
      email: '[email protected]',
      created_at: '2022-09-08T05:53:50.000000Z',
      updated_at: '2022-09-08T05:53:50.000000Z',
    },
  ];

  constructor() {}

  getData(): Observable<any> {
    // used to simulate an API call
    return of(this.data).pipe(delay(2000));
  }
}

forked stackblitz

  • Related