How to use an icon inside MatSlideToggle in Angular Material 11?

Viewed 527

On the Angular Material components overview there's an example of slide toogles with icons:

enter image description here

This looks really nice. Unfortunately this example isn't explained in the actual docs of the component.

So what I tried is this:

<mat-slide-toggle labelPosition="before" color="primary">
  <mat-icon>dark_mode</mat-icon>
  Dark Mode
</mat-slide-toggle>

I have this wrapped inside a menu and the result looks like this:

enter image description here

So it's almost there, but not really. Everything is not aligned correctly.

My questions are:

  • How to align the icon, label and toggle correctly?
  • How is it possible to increase the distance between label and toggle like in the examples from the docs?

Try it on Stackblitz

1 Answers

You can modify the generated CSS in the app.component.css file:

:host ::ng-deep .mat-slide-toggle-content {
  display: flex; /* Turn into a flexbox container for alignment */
}

.material-icons {
  margin-right: 5px; /* Spacing from the content */
}

:host ::ng-deep .mat-slide-toggle-label-before .mat-slide-toggle-bar {
  margin-left: 50px; /* Spacing from the icon and content */
}

It could have been enough to add .mat-slide-toggle-content or .mat-slide-toggle-label-before .mat-slide-toggle-bar but for some reason it was not working. The solution here came handy although it looks unorthodox: CSS style from app.component.css not getting applied to the tabs body content

You can see the full code here: StackBlitz Demo

Related