How to create toggle switch on-off buttons in Angular 4 with [(ngModel)] two way data binding

18,462

Solution 1

use ngx-toggle-switch library

install npm install ngx-toggle-switch --save

Usage:-

import { UiSwitchModule } from 'ngx-toggle-switch';
import { AppComponent } from './app.component';

@NgModule({
  imports: [BrowserModule, UiSwitchModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule {
}

in markup language:-

<ui-switch></ui-switch>

For Two way binding

<ui-switch [(ngModel)]="enable"></ui-switch>

For document of the Packge please refer :- ngx-toggle-switch

Solution 2

You can get the functionality with normal check box and some css. Below is the code which will help.

Css :

.switch {
  position: relative;
  display: inline-block;
  width: 45px;
  height: 20px;
  margin: 20px;
}

.switch input {display:none; background-color: #ccc;}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
   background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 0px;
   right: 0px;
  bottom: -3px;
  background-color: #2196F3;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider:before {
  -webkit-transform: translateX(20px);
  -ms-transform: translateX(20px);
  transform: translateX(20px);
}

/* Rounded sliders */
.slider.round {
  border-radius: 20px;
}

.slider.round:before {
  border-radius: 50%;
}

Html :

<div class="row">
                <label>Yes</label>
                <label class="switch">
                <input type="checkbox" [(ngModel)]="isNewProfile">
                <span class="slider round"></span>
                </label>
                <label>No</label>
        </div>
Share:
18,462
CodeMan
Author by

CodeMan

C# .Net developer with experience on .Net web technologies. Not so good hands on, but even though knows UI stuffs like HTML, CSS, Bootstrap. Love to work on JavaScript and Angular.

Updated on June 13, 2022

Comments

  • CodeMan
    CodeMan almost 2 years

    enter image description here

    Need to implement switch ON-OFF buttons similar to the image attached in question...

  • CodeMan
    CodeMan about 6 years
    Thanks for your solution. But, is it possible to make it with Bootstrap switch on/off button, to make it to look beautiful? And the css styles will be similar to the image attached
  • CodeMan
    CodeMan about 6 years
    Thanks for your solution. I don't want to implement it with any third party plugin or library, that you have suggested. Is it possible to implement with CSS or bootstrap toggle switch with angular4 ??
  • Parth Raval
    Parth Raval about 6 years
    Is there any reason not to use third party plugin or library...?
  • CodeMan
    CodeMan about 6 years
    No specific reason, but want to try the implementation with open source bootstrap or normal css