Mackelito
Mackelito

Reputation: 4421

Conditional button color attr in Angular Material (Components)

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? :)

Upvotes: 7

Views: 8624

Answers (4)

Fahimeh Ahmadi
Fahimeh Ahmadi

Reputation: 1029

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>

Upvotes: 0

javipipero
javipipero

Reputation: 89

<button mat-button [color]=" boolean_condition ? 'accent' : 'primary'">

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

Upvotes: 3

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24406

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 🚀🚀

Upvotes: 1

abney317
abney317

Reputation: 8492

Can just use the ternary operator

[color]="coDeliverySlotView.slotId === bookedSlot.slotId ? 'black' : 'grey'"

Upvotes: 11

Related Questions