如何使用*ngIf实现点击按钮切换显示Angular Material表格
Angular *ngIf 切换表格与按钮实现方案
1. 修改 ts 组件类
你需要在组件中新增一个布尔类型的状态变量,用来控制当前显示的表格和按钮,修改后的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'} ]; @Component({ selector: 'table-basic-example', styleUrls: ['table-basic-example.css'], templateUrl: 'table-basic-example.html', }) export class TableBasicExample { // 注意:原代码的displayedColumns多了不存在的weight、symbol字段,这里修正避免控制台报错 displayedColumns: string[] = ['position', 'name']; dataSource = ELEMENT_DATA.slice(0, 1); maltr = ELEMENT_DATA; // 新增状态变量:true表示当前显示dataSource表格,false表示显示maltr表格 showDataSource = true; }
2. 修改 html 模板
给按钮添加点击事件修改状态变量,同时给按钮、表格添加*ngIf判断显隐,修改后的file.html代码如下:
<!-- 只有不显示dataSource表格时,才显示A按钮,点击后切换为显示dataSource表格 --> <button *ngIf="!showDataSource" (click)="showDataSource = true">A</button> <!-- 只有显示dataSource表格时,才显示B按钮,点击后切换为显示maltr表格 --> <button *ngIf="showDataSource" (click)="showDataSource = false">B</button> <!-- showDataSource为true时显示dataSource绑定的表格 --> <table *ngIf="showDataSource" 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/> <!-- showDataSource为false时显示maltr绑定的表格 --> <table *ngIf="!showDataSource" 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>
逻辑说明
- 初始状态
showDataSource为true,默认显示按钮B、dataSource绑定的表格 - 点击按钮A:将
showDataSource设为true,自动隐藏A按钮、显示B按钮,同时切换为dataSource表格 - 点击按钮B:将
showDataSource设为false,自动隐藏B按钮、显示A按钮,同时切换为maltr表格
内容的提问来源于stack exchange,提问作者adam
相关产品推荐
相关产品推荐

