rob
rob

Reputation: 301

How to add image into Angular Material table column?

I am using an Angular Material table. I wanted to have an icon before the flag text in that column, or how do I add a column with icons? for some reason I can't see how this can be done. My code so far is:

component.ts

export interface PeriodicElement {
  date: string;
  action: string;
  mileage: string;
  author: string;
  flag: string;
}

  const ELEMENT_DATA: PeriodicElement[] = [
  {date: 'xxxxx', action: 'xxxxx', mileage: "xxxxx", author:"xxxxx", flag:"Late"},
  {date: 'xxxxx', action: 'xxxxx', mileage: "xxxxx", author:"xxxxx", flag:"Late"},
  {date: 'xxxxx', action: 'xxxxx', mileage: "xxxxx", author:"xxxxx", flag:"Late"},
];

  displayedColumns: string[] = ['date', 'action', 'mileage', 'author', 'flag'];
  dataSource = new MatTableDataSource(ELEMENT_DATA);

HTML

<ng-container matColumnDef="flag">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Flag</th>
        <td mat-cell *matCellDef="let element" class="status">{{element.flag}} </td>
</ng-container>

Upvotes: 5

Views: 9259

Answers (1)

Fabian K&#252;ng
Fabian K&#252;ng

Reputation: 6183

It is as simple as adding an additional property to your data model, e.g. icon:

export interface PeriodicElement {
  date: string;
  action: string;
  mileage: string;
  author: string;
  flag: string;
  icon: string;
}

Setting the property to whatever icon you want (check icons here):

const ELEMENT_DATA: PeriodicElement[] = [
  {date: 'xxxxx', action: 'xxxxx', mileage: "xxxxx", author:"xxxxx", flag:"Late", icon: "flight_land"},
  {date: 'xxxxx', action: 'xxxxx', mileage: "xxxxx", author:"xxxxx", flag:"Late", icon: "flight_land"},
  {date: 'xxxxx', action: 'xxxxx', mileage: "xxxxx", author:"xxxxx", flag:"Late", icon: "flight_land"},
];

And then using it in your Flag column:

<td mat-cell *matCellDef="let element" class="status"><mat-icon>{{element.icon}}</mat-icon>{{element.flag}}</td>

Here is a simple stackblitz based on the Angular Material table example with an icon displayed based on the property icon defined on the table data.

Upvotes: 8

Related Questions