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

Angular8中通过按钮点击实现HTML表格多列显示与隐藏切换

在Angular 8中实现多表格列的显示/隐藏切换

当然可以!在Angular 8里我们完全可以用更符合框架特性的方式来实现多列的显示/隐藏切换,而且逻辑清晰、易于维护,不用再依赖原生JS的DOM操作啦。下面是一步步的实现方案:

1. 编写组件类逻辑(.ts文件)

首先在你的组件类里定义控制列显示状态的变量,以及切换状态和获取按钮文字的方法:

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

@Component({
  selector: 'app-your-component', // 替换成你实际的组件选择器
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponentComponent {
  // 控制目标列(3、4、6)的显示状态,初始设为显示
  showTargetColumns = true;

  // 切换列的显示/隐藏状态
  toggleTargetColumns() {
    this.showTargetColumns = !this.showTargetColumns;
  }

  // 根据当前状态返回按钮显示的文字
  getButtonLabel(): string {
    return this.showTargetColumns ? '隐藏' : '显示';
  }
}

2. 修改HTML模板

把原来的原生按钮事件替换成Angular的事件绑定,同时给表格添加类绑定来控制样式,还要动态绑定按钮文字:

<button (click)="toggleTargetColumns()">{{ getButtonLabel() }}</button>
<table id="foo" class="table table-sm fs-13px mt-2 mb-5" [class.hide-target-columns]="!showTargetColumns">
 <tr>
 <th class="text-danger fw7 pl-0" colspan="6"> TABLE 1 </th>
 </tr>
 <tr>
 <th class="text-nowrap pr-3 pl-0 sticky-header">Year </th>
 <th class="text-nowrap pr-3 sticky-header">Platform </th>
 <th class="text-nowrap pr-3 sticky-header">Name </th>
 <th class="text-nowrap pr-3 sticky-header">Variants </th>
 <th class="text-nowrap pr-3 sticky-header">Program </th>
 <th class="w-100 sticky-header"></th>
 </tr>
 <tr *ngFor="let u of apiData.unassigned">
 <td class="text-nowrap pr-3 pl-0"> {{ u.year }} </td>
 <td class="text-nowrap text-danger pr-3"> Not Assigned </td>
 <td class="text-nowrap pr-3"> {{ u.modelName }} </td>
 <td class="text-nowrap pr-3"> {{ u.unassignedVariantCount }} </td>
 <td class="text-nowrap pr-3"> {{ u.programCode }} </td>
 <td></td>
 </tr>
 <tr>
 <td colspan="6">&nbsp; </td>
 </tr>
</table>

3. 调整CSS样式

更新你的CSS,针对新增的hide-target-columns类,设置要隐藏的列:

/* 隐藏列3、4、6 */
#foo.hide-target-columns tr > *:nth-child(3),
#foo.hide-target-columns tr > *:nth-child(4),
#foo.hide-target-columns tr > *:nth-child(6) {
  display: none;
}

原理说明

  • 我们用Angular的[class.xxx]属性绑定,当showTargetColumns为false时,自动给表格加上hide-target-columns类,触发CSS隐藏指定列;
  • 按钮点击触发toggleTargetColumns()方法,切换showTargetColumns的布尔值;
  • getButtonLabel()方法根据当前状态动态返回“显示”或“隐藏”,实现按钮文字的切换。

这种方式完全遵循Angular的组件化思想,逻辑和视图分离,以后如果要调整控制的列,只需要修改CSS里的nth-child选择器即可,非常灵活易维护。

内容的提问来源于stack exchange,提问作者Margerine

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 10:12:40