Search code examples
angularangular-materialtogglemat-slider

mat-slide-toggle with 3 states


I am trying to build a mat-slide-toggle button with 3 states which look like something like this in my angular application.

enter image description here

Is there anything like this in the mat-slide-toggle to achieve this?


Solution

  • so based on the state we need to override material styles. look below to see what you need to override.

    click here to see stackblitz example->style.scss file have the overrided styles

    //slide styles
    #one {
      //1st state
      .mat-slide-toggle-thumb-container {
        transform: translate3d(0px, 0, 0) !important;
      }
      .mat-slide-toggle-thumb {
        background-color: red !important;
      }
      .mat-slide-toggle-bar {
        background-color: rgb(219, 123, 123) !important;
      }
    }
    #two {
      //2nd state
      .mat-slide-toggle-thumb-container {
        transform: translate3d(27px, 0, 0) !important;
      }
      .mat-slide-toggle-thumb {
        background-color: blue !important;
      }
      .mat-slide-toggle-bar {
        background-color: rgb(166, 162, 238) !important;
      }
    }
    #three {
      //3rd state
      .mat-slide-toggle-thumb-container {
        transform: translate3d(56px, 0, 0) !important;
      }
      .mat-slide-toggle-thumb {
        background-color: green !important;
      }
      .mat-slide-toggle-bar {
        background-color: rgb(93, 197, 102) !important;
      }
    }
    .mat-slide-toggle-bar {
      //slide width
      width: 75px !important;
    }
    
    

    it's your responsibility to change the state in the typescript file based on your logic.

    <mat-card class="result">
      <mat-card-content>
        <h2 class="example-h2">Result</h2>
    
        <section class="example-section" [id]="mystatus">
          <mat-slide-toggle class="example-margin" (click)="change()">
            Slide me!- now i'm {{mystatus}} state
          </mat-slide-toggle>
        </section>
      </mat-card-content>
    </mat-card>