【问题标题】:How to color conditionally a cell for ngx-datatable如何有条件地为 ngx-datatable 的单元格着色
【发布时间】:2020-05-19 11:11:42
【问题描述】:

如果输入为负数,我想更改单元格/值的颜色。我知道 getCellClass 函数内部应该有更多参数,但我不知道如何正确处理它们,因为 ngx-datatable 的文档不容易理解。

TS-文件, CSS 文件, HTML 文件,

getCellClass(row: RowObject) {
  return {
    'ngx-datatable-value-negative': row.value <= 0
  };
}
.ngx-datatable-value-negative {
  color: red !important;
}
<ngx-datatable>
  <ngx-datatable-column [cellClass]="getCellClass" [resizeable]="false" [width]="50" prop="openTimeInHours" [summaryTemplate]="templateForOpen" headerClass="text-right">
    <ng-template ngx-datatable-header-template let-column="column">
      <span title="Tooltip">Column Name</span>
    </ng-template>
    <ng-template let-value="value" ngx-datatable-cell-template>
      <div class="text-right">
        {{value | number: '1.2-2'}}
      </div>
    </ng-template>
  </ngx-datatable-column>
</ngx-datatable>

【问题讨论】:

    标签: angular typescript ngx-datatable


    【解决方案1】:

    您是否尝试过使用 [ngclass] 选择器?

    getCellClass(value: number) {
      return {
        'ngx-datatable-value-negative': value <= 0
      };
    }
    
    .ngx-datatable-value-negative {
      color: red !important;
    }
    
    <ngx-datatable>
      <ngx-datatable-column [resizeable]="false" [width]="50" prop="openTimeInHours" [summaryTemplate]="templateForOpen" headerClass="text-right">
        <ng-template ngx-datatable-header-template let-column="column">
          <span title="Tooltip">Column Name</span>
        </ng-template>
        <ng-template let-value="value" [ngclass]="getCellClass(value)" ngx-datatable-cell-template>
          <div class="text-right">
            {{value | number: '1.2-2'}}
          </div>
        </ng-template>
      </ngx-datatable-column>
    </ngx-datatable>
    

    【讨论】:

    • 非常感谢,但您的方法当时并没有解决我的问题。
    【解决方案2】:

    我解决了我的问题。重要的是要了解 getClass 需要一个已定义的对象。就像在 ngx-documentation 中一样,我也注意到了返回类型 any。

    我将它记录在我的控制台中,这样我就可以正确地处理课程了

    getCellClass(a: any): any {
      console.log(a);
      return {
        'ngx-datatable-value-negative': value <= 0
      };
    }
    

    这样我得到了这个对象:

    {row: {…}, group: undefined, column: {…}, value: -0.5, rowHeight: "auto"}
    

    此外,我可以使用我新创建的 NgxDatatableCell 类来传递 cellClass 的预期对象

        export class NgxDatatableCell {
        value: number;
    }
    
    

    这就是我的方法现在的样子

    getCellClass(row: NgxDatatableCell): any {
        return {
            'ngx-datatable-value-negative': row.value < 0,
        };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-12
      • 2016-03-19
      • 2012-10-15
      • 1970-01-01
      • 1970-01-01
      • 2014-05-04
      相关资源
      最近更新 更多