Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 907
Mackelito Avatar asked Sep 16 '19 20:09

Mackelito


3 Answers

Can just use the ternary operator

[color]="coDeliverySlotView.slotId === bookedSlot.slotId ? 'black' : 'grey'"
like image 115
abney317 Avatar answered Nov 07 '22 19:11

abney317


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

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

like image 2
javipipero Avatar answered Nov 07 '22 21:11

javipipero


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

like image 1
Muhammed Albarmavi Avatar answered Nov 07 '22 21:11

Muhammed Albarmavi