Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular material mat-slide-toggle change toggle icon

I am using angular6 to layout my UI.

The default mat-slide-toggle button looks like this:

enter image description here

But i want the toggle button to look like below from the material-icons toggle_on , toggle_off

enter image description here

Is it possible to customize it?

Thanks a lot.

like image 815
rodent_la Avatar asked Nov 16 '25 19:11

rodent_la


2 Answers

You could overwrite the default styling that is being applied to the Material slide toggle component. I must warn you, this is a bit hacky to do so. However, here's my take on your screenshot.

Slide toggle example

Styling that is needed for this:

.mat-slide-toggle-thumb {
    width: 10px !important;
    height: 10px !important;
    transform: translate(50%, 50%);
}

.mat-slide-toggle-bar {
  background-color: #000;
  border-radius: 15px !important;
  height: 16px !important;
}

.mat-slide-toggle-thumb-container {
  top: -2px !important;
}

.mat-slide-toggle.mat-checked:not(.mat-disabled) .mat-slide-toggle-bar {
  background-color: #000;
}

.mat-slide-toggle.mat-checked:not(.mat-disabled) .mat-slide-toggle-thumb {
  background-color: #fff;
}

Unfortunately, some !important is needed to overrule the default styling that is set by Angular's Material CSS. You can view the example on StackBlitz.

like image 176
Roy Avatar answered Nov 18 '25 09:11

Roy


I got into this question when I wanted to know how to add an icon in the center of the material mat-slide-toggle

How to add icon in the center of material slide toggle?

We need to slide toggle has a icon in the center of it (here you see Google Crhome icon in the center of the toggle button), something like the image bellow:

enter image description here

What you'll need to do is to set your desired image (as an icon) as background-image of the toggle button (.mat-slide-toggle-thumb)

.mat-slide-toggle-thumb {
    width: 18px !important;
    height: 18px !important;
    transform: translate(0%, 0%);
  background-image: url(https://cdn0.iconfinder.com/data/icons/flat-round-system/512/chrome_browser-512.png) !important;
  background-origin: content-box;
  background-size: contain;
  background-position: center center;
}

.mat-accent .mat-slide-toggle-thumb{
  filter: grayscale(100%);
}

.mat-checked .mat-slide-toggle-thumb{
  filter: grayscale(0);
}

Here is the working example demo on StackBlitz

Note: I used the code snippet provided by the accepted answer.

like image 23
Mohammad Kermani Avatar answered Nov 18 '25 08:11

Mohammad Kermani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!