简体   繁体   English

如何使用 [(ngModel)] 两种方式数据绑定在 Angular 4 中创建切换开关开关按钮

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

在此处输入图像描述

Need to implement switch ON-OFF buttons similar to the image attached in question...需要实现类似于所附图像的开关开关按钮......

use ngx-toggle-switch library使用ngx-toggle-switch

install npm install ngx-toggle-switch --save安装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打包文档请参考:- ngx-toggle-switch

You can get the functionality with normal check box and some css.您可以通过普通复选框和一些 css 获得功能。 Below is the code which will help.下面是有帮助的代码。

Css : 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>

This works on my site这适用于我的网站

 <div class="custom-control custom-switch pt-4"> <input type="checkbox" class="custom-control-input" id="activeStatus" name="activeStatus" [(ngModel)]="user.activeStatus"> <label class="custom-control-label" for="activeStatus">Is Active</label> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM