首页 > 解决方案 > 使用 ngStyle 为粘性列设置 Angular 材质数据表标题左侧 CSS 属性?

问题描述

在这个演示中,我试图将动态的leftCSS 属性设置为使用,但看起来 Angular 用它认为应该是的值覆盖了值......在应用更新后。CUSTOMER mat-header-cell64pxngStyle216pxngStyle

https://stackblitz.com/edit/angular-material-data-table-module-styling-sticky-column-adjust

关于如何解决这个问题的想法?

标签: htmlcssangulartypescriptangular-material

解决方案


正如您所说,由于某些默认覆盖,它不会占用 64px。在这种情况下,我们需要使用 left:64px !important。但是使用 ngStyle 时不支持使用 '!important'。因此,我们在 css 文件中定义了一个新类

    .leftMargin {
      left: 64px !important;
    }

并且在 ngFor 循环中,我们仅在列名为“客户”时应用此 css 类。

     <ng-container *ngFor="let c of COLUMNS" matColumnDef="{{c.toUpperCase()}}" [sticky]="isSticky(c)">
            <mat-header-cell [ngClass]="{'leftMargin': c=='CUSTOMER'}" [ngStyle]="styleHeaderCell(c)" *matHeaderCellDef mat-sort-header>
              {{c.toUpperCase().split('_').join('')}}
            </mat-header-cell>
            <mat-cell *matCellDef="let row;">{{row[c.toLowerCase()] ? row[c.toLowerCase()] : row[c.toUpperCase()]}}
            </mat-cell>
     </ng-container>

请参阅此 stackblitz 列表:https ://stackblitz.com/edit/angular-material-data-table-module-styling-sticky-column-cywshb?file=src%2Fapp%2Fapp.component.html


推荐阅读