首页 > 解决方案 > Angular - 选中复选框时隐藏/显示表格中的列

问题描述

单击复选框时,我试图隐藏整个列以及该列中的所有元素。我想知道使用 Angular 解决这个问题的最佳方法是什么。

 <table class="table">
                    <thead>
                    <tr>
                        <th scope="col">Name</th>
                        <th scope="col">Email</th>
                        <th scope="col">Date</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr *ngFor="let user of Items" >
                        <td>{{user.Name}}</td>
                        <td>{{user.Email}}</td>
                        <td>{{user.Date}}</td>
                    </tr>
                    </tbody>
                </table>

在表格上方我有 3 个复选框:

姓名 | 电子邮件 | 日期

我想按其中一个,然后整列消失,包括<th>元素和<td>元素。解决这个问题的最佳主意是什么?

标签: javascripthtmlangular

解决方案


声明类

  export class ColumnVisible{
       public nameVisible:boolean=true;
       public emailVisible:boolean=true;
       public dateVisible:boolean=true;
       constructor(){}
    }

在组件中调用它

columnVisible:ColumnVisible;

在构造函数中初始化它

this.columnVisible=new ColumnVisible();

inhtml 写为类并给出点击事件

<input [(ngModel)]="columnVisible.nameVisible" type="checkbox"(change)="columnVisible.nameVisible=!columnVisible.nameVisible" /> 
<input [(ngModel)]="columnVisible.emailVisible" type="checkbox"(change)="columnVisible.emailVisible=!columnVisible.emailVisible" /> 
<input [(ngModel)]="columnVisible.dateVisible" type="checkbox"(change)="columnVisible.dateVisible=!columnVisible.dateVisible" /> 
    <table class="table">
        <thead>
        <tr>
            <th  ngIf="columnVisible.nameVisible" scope="col">Name</th>
            <th  ngIf="columnVisible.emailVisible" scope="col">Email</th>
            <th  ngIf="columnVisible.dateVisible" scope="col">Date</th>
        </tr>
        </thead>
        <tbody>
        <tr *ngFor="let user of Items" class="{{user.IsShown}}" >
            <td ngIf="columnVisible.nameVisible" >{{user.Name}}</td>
            <td ngIf="columnVisible.emailVisible">{{user.Email}}</td>
            <td ngIf="columnVisible.dateVisible">{{user.Date}}</td>
        </tr>
        </tbody>
    </table>

推荐阅读