Junior Gantin
Junior Gantin

Reputation: 2192

How can I add 'on', 'off' label to mat-slide-toggle?

Right now, I have a slide-toggle like this:

<mat-slide-toggle
    class="toggle">
</mat-slide-toggle>

enter image description here

How can I add on, off label like below?

enter image description here

enter image description here

Upvotes: 2

Views: 6621

Answers (2)

G. Tranter
G. Tranter

Reputation: 17908

You can hack this with CSS, but it's really hacky. In your host wrapper component .scss:

:host {
  .mat-slide-toggle {
    &.mat-checked {
      ::ng-deep.mat-slide-toggle-bar::after {
        content: 'ON';
        font-size: 45%;
        font-weight: 700;
        color: black;
        position: absolute;
        left: 4px;
        top: -5px;
      }
    }
    &:not(.mat-checked) {
      ::ng-deep.mat-slide-toggle-bar::after {
        content: 'OFF';
        font-size: 45%;
        font-weight: 700;
        color: white;
        position: absolute;
        left: 21px;
        top: -5px;
      }
    }
  }
}

StackBlitz

Upvotes: 4

user733421
user733421

Reputation: 497

Angular material components are not build to be extendable check: https://github.com/angular/components/issues/10208

Instead you can create your own custom form field check: https://material.angular.io/guide/creating-a-custom-form-field-control

Upvotes: 0

Related Questions