How to use ng-if for display table

Issue

I have two tables (1 and 2) and two buttons A and B.
I want when I click on the button A displays me the dataSource and button B
and when I click on the button B displays me the maltr and button A

I have already created the 2 tables with Angular Material.

what should i do to find a solution? I can do with *ngIf

file.html:

   <button>A</button>
    <button>B</button>
    <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
    
      <ng-container matColumnDef="position">
        <th mat-header-cell *matHeaderCellDef> No. </th>
        <td mat-cell *matCellDef="let element"> {{element.position}} </td>
      </ng-container>
    
      <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef> Name </th>
        <td mat-cell *matCellDef="let element"> {{element.name}} </td>
      </ng-container>
    
      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
    </table>

<br/>

 <table mat-table [dataSource]="maltr" class="mat-elevation-z8">
    
      <ng-container matColumnDef="position">
        <th mat-header-cell *matHeaderCellDef> No. </th>
        <td mat-cell *matCellDef="let element"> {{element.position}} </td>
      </ng-container>
    
      <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef> Name </th>
        <td mat-cell *matCellDef="let element"> {{element.name}} </td>
      </ng-container>
    
      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
    </table>

file.ts:

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

export interface PeriodicElement {
  name: string;
  position: number;
}

const ELEMENT_DATA: PeriodicElement[] = [
  {position: 1, name: 'Hydrogen'},
  {position: 2, name: 'Helium'},
  {position: 3, name: 'Lithium'},
  {position: 4, name: 'Beryllium'},
  {position: 5, name: 'Oxygen'}
];

/**
 * @title Basic use of `<table mat-table>`
 */
@Component({
  selector: 'table-basic-example',
  styleUrls: ['table-basic-example.css'],
  templateUrl: 'table-basic-example.html',
})
export class TableBasicExample {
  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = ELEMENT_DATA.slice(0, 1);
  maltr = ELEMENT_DATA;
}

Solution

Danday’s answer works too, but I would use just one button. Less html to maintain.

Template:

<table *ngIf="showTable1" class="table2">...</table>

<table *ngIf="!showTable1" class="table1">...</table>

<button (click)="toggleTable()">button {{ showTable1 ? 'A' : 'B' }}</button>

Your .ts:

showTable1 = true

toggleTable() {
  this.showTable1 = !this.showTable1
}

Answered By – H3AR7B3A7

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.