ssct79
ssct79

Reputation: 403

mat-button-toggle-checked with dynamic style + Angular 6

I'm trying to customize my button-toggle when it is checked but my current code is not working...

Here is the actual code

<mat-button-toggle-group #mytoggle (change)="selectoption($event)" value="{{num}}">
            <mat-button-toggle [style.background-color]="getColor(op)" *ngFor="let op of mylist" [value]="op">{{op}}</mat-button-toggle>
        </mat-button-toggle-group>

Here is my method on .ts

 getColorChecked(opcao: any){
        if ( opcao === 2){
            return '#EA0B28 !important;';
        }else{
            return '#9d9b9a !important;';
        }
    }

Here is my scss file

.mat-button-toggle-group, .mat-button-toggle-standalone{
  box-shadow: 0 3px 1px -2px rgba(0,0,0,.02), 0 2px 2px 0 rgba(0,0,0,.01), 0 1px 5px 0 rgba(0,0,0,.12);
}   
 .mat-button-toggle{
      border-right: 1px solid #cccccc40 !important;
      font-weight: 400;
      width: 50px !important;
      padding: 0px !important;
      background: #f7f9fbc7 !important;
      div{
        padding: 0px !important;
      }
    }
    .mat-button-toggle-checked {
      color: #fbfbfb;
    }

It's not working... There's a best way to do that?

Upvotes: 1

Views: 3365

Answers (1)

Quentin
Quentin

Reputation: 1933

Solution 1: Same color for all selected buttons

You can add these CSS Class:

.mat-button-toggle-appearance-standard {
    background-color: #9d9b9a;
    color:white;
}

.mat-button-toggle-checked {
    background-color: #EA0B28;
    color:white;
}

enter image description here


Solution 2: Single color by selected buttons

You can add these CSS Class: :nth-child(x) Target items based on their position in the document

.bg-red:nth-child(1) {
    background-color: red;
    color:white;
}

.bg-green:nth-child(2) {
    background-color: green;
    color:white;
}

.bg-blue:nth-child(3) {
    background-color: blue!important;
    color:white;
}

HTML:

<mat-button-toggle-group>
  <mat-button-toggle *ngFor="let op of mylist" 
    [value]="op" 
    [ngClass]="{'bg-red':selected === 1,'bg-green':selected === 2,'bg-blue':selected === 3}" 
    (click)="selected = op"> {{op}}
  </mat-button-toggle>
</mat-button-toggle-group>

TS:

export class ButtonToggleOverviewExample {
  mylist = [1,2,3];
  selected;
}

enter image description here


StackBlitz

Upvotes: 0

Related Questions