Bhargavi
Bhargavi

Reputation: 313

Show table on button click in angular

On clicking the scan button, mat table should be displayed.

app.component.html:

 <button class="btn btn-primary">Scan</button>
 <div class="table-responsive">
 <table class="table-bg" mat-table [dataSource]="dataSource" matSort>
 <div>
 <ng-container matColumnDef="slNo">
 <th mat-header-cell *matHeaderCellDef mat-sort-header> Sl. No.</th>
 <td mat-cell *matCellDef="let item ; let i= index">{{ i + 1 }}</td>
 </ng-container>
 <ng-container matColumnDef="name">
 <th mat-header-cell *matHeaderCellDef mat-sort-header> Name</th>
 <td mat-cell *matCellDef="let item ; let i= index">{{name}} </td>
 </ng-container>
 </div>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row;  columns: displayedColumns;"></tr>
 </table>
</div>

Upvotes: 0

Views: 6420

Answers (1)

Adam DP
Adam DP

Reputation: 36

you can accomplish this using an *ngIf.

In the typescript file (app.component.ts) create a new variable called showTable and set it to be false by default.

showTable: boolean = false;

we will then make it so that the button toggles this to be true or false by creating a function that the button will call. Put this function in app.component.ts as well

toggleShowTable(): void {
    this.showTable = !this.showTable;
}

Finally, we will add the code to your html to make this all work.

Add a (click) function to your button like so:

 <button (click)='toggleShowTable()' class="btn btn-primary">Scan</button>

And add an *ngIf to the opening tag of your table like so:

 <table *ngIf='showTable' class="table-bg" mat-table [dataSource]="dataSource" matSort>

Your table will now not show by default but once you click the button it will begin to show.

Upvotes: 2

Related Questions