You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用*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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 01:18:00