Using [ngStyle] to apply custom color to mat-raised-button

Viewed 225

I want to use a custom mat-button color style but it's not working when I combine it with an [ngStyle].

This is what I want:

html:

<button mat-raised-button
        [ngStyle]="getDirectionArrowStyle(item.label, 'ltr')"
        value="ltr"
        aria-label="Left To Right"
        (click)="setActiveDirection(item.label, 'ltr')">
   <mat-icon>east</mat-icon>
</button>

css:

.mat-arrow-selected {
  background-color: green;
  color: #fff;
}

.mat-arrow-deselected {
  background-color: red;
  color: #fff;
}

The transform is working fine but the color is not.

typescript:

getDirectionArrowStyle(label: string, directionValue: string) {
  const isActiveDirection = this.isActiveDirection(label, directionValue);
  const styles = {
    color: isActiveDirection ? 'arrow-selected' : 'arrow-deselected',
    transform: isActiveDirection ? 'scale(1.2)' : 'scale(0.5)'
  };
  return styles;
}

The html below works so the custom mat-button color is working.

html:

<button mat-raised-button
        color="arrow-selected"
        value="ltr"
        aria-label="Left To Right"
        (click)="setActiveDirection(item.label, 'ltr')">
   <mat-icon>east</mat-icon>
</button>

I could use an *ngIf="isActiveDirection(label, directionValue)" and have two button elements. One with color="arrow-selected" and the other with color="arrow-deselected" but the cleaner solution would be via the [ngStyle]. So I would be very happy if this is possible.

All help or tips are welcome.

1 Answers

I presume your theme has those color names in it? The color attribute is special for the material controls. It is not CSS. ngStyle returns CSS.

Try:

<button mat-raised-button
        [ngStyle]="getDirectionArrowStyle(item.label, 'ltr')"
        [color]="getDirectionColour(item.label, 'ltr')"
        value="ltr"
        aria-label="Left To Right"
        (click)="setActiveDirection(item.label, 'ltr')">
   <mat-icon>east</mat-icon>
</button>

You'll need another function to get the colour name:

getDirectionColour(label: string, directionValue: string) {
  const isActiveDirection = this.isActiveDirection(label, directionValue);
  return isActiveDirection ? 'arrow-selected' : 'arrow-deselected';
}
Related