【问题标题】:Hide Angular material 2 table, specific header and its column隐藏 Angular 材料 2 表、特定标题及其列
【发布时间】:2017-11-11 06:28:30
【问题描述】:

我只是试图隐藏一个 Angular material 2 表 statusid 标题和列,如下所示。

        <mat-table class="mat-elevation-z1" #table [dataSource]="dataSourceHE">
            <ng-container hidden="hidden" cdkColumnDef="statusid">
                <mat-header-cell hidden="hidden"> Id </mat-header-cell>
                <mat-cell hidden="hidden"> {{row.statusid}} </mat-cell>
            </ng-container>
         </mat-table>

但这不能正常工作。如果可能的话,我该怎么做?

【问题讨论】:

    标签: angular angular-material2


    【解决方案1】:

    您只需要更改组件中的 Column Map。添加或删除其中的任何键都会导致表格显示或隐藏相应的列。

    不要尝试使用 CSS 或 HTML 解决方案,例如使用 hidden 属性或 display: none; CSS 规则,它们会使代码变得肮脏且容易出错。

    【讨论】:

    • 我相信应该选择这个答案。效果很好。
    【解决方案2】:

    解决办法是创建一个属性指令,通过这个指令我们可以设置一个元素的显示属性。

    showcolumn.directive.ts:

    import {Component, Directive, ElementRef, Input, AfterViewInit} from '@angular/core';
    @Directive({ 
         selector: '[showColumn]' 
    })
    export class ShowColumnDirective implements AfterViewInit{
        @Input() showInput: string;
        constructor(private elRef: ElementRef) { 
        }
        ngAfterViewInit(): void {
        this.elRef.nativeElement.style.display = this.showInput;
        }
    }
    

    在您应用的模块或任何其他模块中声明此指令:

    import {ShowColumnDirective} from './showcolumn.directive';
    @NgModule({
      declarations: [ShowColumnDirective]
    })
    export class AppModule {}
    

    现在我们可以在表格的 html 组件中使用指令:

    <ng-container matColumnDef="position">
      <mat-header-cell showColumn showInput="none" *matHeaderCellDef> No. </mat-header-cell>
      <mat-cell showColumn showInput="none" *matCellDef="let element"> {{element.position}} </mat-cell>
    </ng-container>
    

    这是一个演示:https://plnkr.co/edit/Woyrb9Yx8b9KU3hv4RsZ?p=preview

    【讨论】:

    • 这太复杂了——你甚至可以这样做: Id​​eader-cell>
    【解决方案3】:

    只需删除标题行。例如,只有一列'title'

    <ng-container matColumnDef="title">
       <td *matCellDef="let item" mat-cell>{{item}}</td>
    </ng-container> 
    <tr matRowDef="let row;columns: ['title'];" mat-row></tr>  
    

    【讨论】:

      猜你喜欢
      • 2019-03-08
      • 2018-09-22
      • 1970-01-01
      • 2018-06-01
      • 1970-01-01
      • 2018-11-30
      • 1970-01-01
      • 1970-01-01
      • 2018-03-19
      相关资源
      最近更新 更多