首页 > 解决方案 > How to convert color code into actual color

问题描述

I'm using Angular material with Angular6 in my project. What I want to do is convert color codes which stored in the database into actual colors in my mat-table.

Currently, my table is as follows, enter image description here

This is how I'm getting visible columns data from my component.ts file,

getIssueCategory() {
  this.IssueService.getAllIssueCategories().subscribe(result => {
      this.issueCategoryDTOList = result.reverse();

      //updating data source
      this.updatingDataSource(result);

      this.IssueService.issueCategoryDTOList = result;
    }
  );
}

get visibleColumns() {
  return this.displayedColumns.filter(column => column.visible).map(column => column.property);
}

applyFilter(filterValue: string) {
  this.dataSource.filter = filterValue.trim().toLowerCase();
}

The color column in my HTML file is as follows,

<!-- color Column -->
    <ng-container matColumnDef="color">
      <mat-header-cell *matHeaderCellDef mat-sort-header="color" style="max-width: 25%; min-width: 25%;">COLOR
      </mat-header-cell>
      <mat-cell *matCellDef="let element" style="text-transform: uppercase; max-width: 25%; min-width: 25%;">
        {{element.color}}
      </mat-cell>
    </ng-container>

Finally to getting understand easier I have designed my expected output using photoshop, enter image description here

PS: In my database, the colors are stored as color codes.

标签: cssangularuitableviewmat-table

解决方案


You can simply do something like -

<!-- color Column -->
<ng-container matColumnDef="color">
   <mat-header-cell *matHeaderCellDef mat-sort-header="color" style="max-width: 25%; min-width: 25%;">COLOR
   </mat-header-cell>
   <mat-cell *matCellDef="let element" style="text-transform: uppercase; max-width: 25%; min-width: 25%;">
     <div style="width: 15px; height: 15px" [style.background-color]="element.color">/div>
   </mat-cell>
</ng-container>

Or perhaps a better way would be to turn it into a component

@Component({
  selector: 'app-color-swatch',
  template: `<div [style.background-color]="colorCode"></div>`,
  styles: ['div { height: 15px; width: 15px }']
})
export class ColorSwatchComponent {

  @Input colorCode: string;

}

Then -

<app-color-swatch [color]="element.color"></app-color-swatch>

推荐阅读