Home > database >  Changing button background colour based on the element of the table-element
Changing button background colour based on the element of the table-element

Time:07-11

I have to make a table something of this sort.SEE STATUS COLUMN

I want the button colour to be decided based on the value of the button text. How cann I do it?

 <ng-container matColumnDef="status">
      <th mat-header-cell *matHeaderCellDef>Status</th>
      <td mat-cell *matCellDef="let element">
        <button mat-raised-button [style.background-color]="element.status ==='COMPLETED' ? 'lightgreen': (element.status ==='ABORTED'? 'lightred':'' )">
          {{ element.status }}
        </button>
      </td>
    </ng-container>

I wrote this but this only works for lightgreen, the other colours dont get displayed. How should I do this for multiple status values in the Status Column?

CodePudding user response:

Add a function to your component that returns the desired color based on the status:

class YourComponent {
  getButtonColor(status: string) {
    switch(status) {
      case 'COMPLETED': return 'lightgreen';
      case 'ABORTED': return 'lightred';
      default: return '';
    }
  } 
}

And then use that function in your template:

<button mat-raised-button [style.background-color]="getButtonColor(element.status)">
  {{ element.status }}
</button>

Instead of the switch statement in the component, you can also opt to create a mapping object that maps statuses to colors.

CodePudding user response:

You could do it using scripts :

<ng-container matColumnDef="status">
      <th mat-header-cell *matHeaderCellDef>Status</th>
      <td mat-cell *matCellDef="let element">
        <button mat-raised-button #coloredButton">
          {{ element.status }}
        </button>
      </td>
    </ng-container>

In your component-name.ts

@ViewChild('coloredButton') coloredButton : ElementRef<HtmlButtonElement>;

changeColor() : void {
  if(!this.coloredButton?.nativeElement) return;
  // your color code here
  this.coloredButton.nativeElement.style.backgroundColor = '#FFFFFF';
}

Edit: You could also do it like Robby Cornelissen answered.

  • Related