Изменить цвет элемента в таблице [ng-class] на основе условия - PullRequest
1 голос
/ 28 сентября 2019

Я застрял и мне нужна помощь.

У меня есть таблица с именем столбца deadLine.

Данные получены из MySQL и имеют свойства DATETIME.Я создал функцию, которая проверяет, прошла ли дата в столбце сегодняшняя дата.Теперь я хочу, чтобы при условии true этот конкретный элемент в таблице был красного цвета.

Это мой компонент:

import { Component, ViewChild, OnInit } from '@angular/core';
import { ReportsService } from '../../../../core/services/reports.service';
import { Reports } from 'src/app/shared/entity/reports.entity';
import { MatTableDataSource, MatPaginator, MatPaginatorIntl } from '@angular/material';
import { Utils } from '../../../../shared/utils';
import { formatDate } from '@angular/common';


@Component({
    selector: 'app-reports',
    templateUrl: './reports.component.html',
    styleUrls: ['./reports.component.sass'],
    providers: [
        { provide: MatPaginatorIntl, useValue: Utils.hebrewPaginator() }
    ]
})
export class ReportsComponent implements OnInit {
    public dataSource: MatTableDataSource<Reports>;
    public displayedColumns: string[] = ['deadLine', 'year', 'type', 'companyID', 'companyName'];
    @ViewChild('paginator', { read: MatPaginator, static: false }) paginator: MatPaginator;
    filterBool: Boolean;
    dataForFilter: Array<Reports>;


    constructor(private service: ReportsService) { }

    ngOnInit() {
        this.service.getReports((data) => this.onGetReportsList(data));

    }
    onGetReportsList(data) {
        data.map((report) => {
            const format = 'yyyy.MM.dd';
            const locale = 'en-US';
            report.deadLine = formatDate(report.deadLine, format, locale);
            const repDate = new Date(report.deadLine).getTime();
            const nowDay = new Date().getTime();
            if (nowDay > repDate) {
                report.deadLine += '*';
            }
        });
        this.dataForFilter = data;
        this.dataSource = new MatTableDataSource<Reports>(data);
        this.dataSource.paginator = this.paginator;
    }
}

Это файл HTML.

<div class="container">
    <div class="flex-menu">
        <app-home-menu (filterEvent)="applyFilter($event)" [dataSource]="dataSource"></app-home-menu>
    </div>
    <div class="mat-elevation-z8">
        <table mat-table [dataSource]="dataSource">
            <ng-container matColumnDef="companyName">
                <th mat-header-cell *matHeaderCellDef> CompanyNme </th>
                <td mat-cell *matCellDef="let element"> {{element.companyName}} </td>
            </ng-container>


            <ng-container matColumnDef="companyID">
                <th mat-header-cell *matHeaderCellDef> HP </th>
                <td mat-cell *matCellDef="let element"> {{element.companyID}} </td>
            </ng-container>

            <ng-container matColumnDef="type">
                <th mat-header-cell *matHeaderCellDef> Type </th>
                <td mat-cell *matCellDef="let element"> {{ element.name}} </td>
            </ng-container>


            <ng-container matColumnDef="year">
                <th mat-header-cell *matHeaderCellDef> Year </th>
                <td mat-cell *matCellDef="let element"> {{element.year}} </td>
            </ng-container>

            <ng-container matColumnDef="deadLine">
                <th mat-header-cell *matHeaderCellDef> DeadLine </th>
                <td mat-cell *matCellDef="let element"> {{element.deadLine}} </td>
            </ng-container>

            <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
            <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
        </table>
        <mat-paginator #paginator [pageSizeOptions]="[10, 20, 30]" [showFirstLastButtons]="true"></mat-paginator>
    </div>
</div>

Ответы [ 2 ]

1 голос
/ 28 сентября 2019

Если вы хотите просто добавить цвет red, проще всего было бы динамически добавить стиль на основе того, есть ли у deadLine звездочка *, поскольку вы добавляете его для прошедших сроков.

<td mat-cell [style.color]="isDue(element.deadLine) ? 'red' : ''" *matCellDef="let element"> {{element.deadLine}} </td>

Если вы хотите добавить класс, используйте ngClass

<td mat-cell [ngClass]="{'deadline': isDue(element.deadLine)}" *matCellDef="let element"> {{element.deadLine}} </td>
<!-- OR -->
<td mat-cell [class.deadline]="isDue(element.deadLine)" *matCellDef="let element"> {{element.deadLine}} </td>

, где функция isDue выглядит следующим образом

today: number = new Date().getTime();

isDue(date): boolean {
    return this.today > new Date(date).getTime();
}

иdeadline класс

.deadline {
    color: red;
    /* Add other css properties here */
}
0 голосов
/ 28 сентября 2019

Если вы хотите выделить всю строку, вы можете

<tr mat-row *matRowDef="let row; columns: displayedColumns;" [class.highlightRow]="highlight(row)"></tr>

В случае, если вы просто хотите выделить ячейку

<ng-container matColumnDef="deadLine">
                <th mat-header-cell *matHeaderCellDef> DeadLine </th>
                <td mat-cell [class.highlightRow]="highlight(element)" *matCellDef="let element"> {{element.deadLine}} 
                </td>
</ng-container>

В файле .ts

highlight(row) {
  //Check if condition true or false
  if(true) {
    return true;
  } else {
    return false;
  }
}

Согласно коду, если условие истинно, класс 'highlightRow' будет применен к этой конкретной строке, и вы можете соответственно стилизовать его в css.

Рабочий пример: https://stackblitz.com/edit/angular-pgypvo

...