7

I have a component that takes an Input.. @Input() coDeliveryCandidates: DeliverySlotView[];

this is used in the template:

<ng-container *ngFor="let coDeliverySlotView of (coDeliveryCandidates | async)">
  <button
    mat-raised-button
    [color]=""
  >
    {{ label  }}
  </button>
</ng-container>

color attribute takes a string as value and I would like to do something like:

[color]="{
  black: coDeliverySlotView.slotId === bookedSlot.slotId,
  grey: !coDeliverySlotView.slotId === bookedSlot.slotId
}"

Here I use the same syntax as ngClass but I guess it's not supported in that way.. so what other similar ways are there? :)

Mackelito
  • 4,213
  • 5
  • 39
  • 78

4 Answers4

11

Can just use the ternary operator

[color]="coDeliverySlotView.slotId === bookedSlot.slotId ? 'black' : 'grey'"
abney317
  • 7,760
  • 6
  • 32
  • 56
  • angular material has some preset color like *primary,accent,warn* that why 'black' , 'gray' will not work ,you are correct in case this was a preset – Muhammed Albarmavi Sep 17 '19 at 11:56
3
<button mat-button [color]=" boolean_condition ? 'accent' : 'primary'">

This is a possible easy example using the color of material.

javipipero
  • 89
  • 9
  • what if we have more then 2 condition, in my case I have 3 condition how will that look like?? – ZAJ Jul 06 '22 at 15:05
1

material design has built in three color called primary,accent,warn and base of the value you pass to color will set the need class , in this case the easy way to change the color is defined a class without set the color property

style.scss

.black {
  &.mat-raised-button.mat-button-base {
    background: black ;
    color:#fff ;
  }
}

.gray {
  &.mat-raised-button.mat-button-base {
    background: #ccc ;
    color:#555 ;
  }
}
.orange {
  &.mat-raised-button.mat-button-base {
    background: orange ;
    color:#fff ;
  }
}

template

<button mat-raised-button class="black">black</button>
<button mat-raised-button class="gray">gray</button>
<button mat-raised-button class="orange">orange</button>

set the class base of condition by ngClass directive and boolean property like this

 <button mat-raised-button 
        [ngClass]="{'black': isBlack , 'gray' : !isBlack}" (click)="isBlack =!isBlack" >
        click to toggle
 </button>

demo

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91
  • We already have our own theme and the colors are present.. the question was simple about conditional... – Mackelito Sep 17 '19 at 20:51
0

I used this method

Component

isActive = false;

html

<input type="checkbox" [(ngModel)]="isActive">    

<button mat-raised-button [color]="isActive ? 'warn' : 'warn'">
        {{isActive ? 'warn' : 'warn'}}
</button>
Fahimeh Ahmadi
  • 813
  • 8
  • 13