【问题标题】:How to create toggle switch on-off buttons in Angular 4 with [(ngModel)] two way data binding如何使用 [(ngModel)] 两种方式数据绑定在 Angular 4 中创建切换开关开关按钮
【发布时间】:2018-10-07 21:45:38
【问题描述】:

需要实现类似于所附图片的开关开关按钮...

【问题讨论】:

标签: javascript css html angular twitter-bootstrap


【解决方案1】:

您可以使用普通复选框和一些 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>

【讨论】:

  • 感谢您的解决方案。但是,有没有可能用 Bootstrap 的开关按钮来让它看起来很漂亮?并且 css 样式将类似于附加的图像
【解决方案2】:

使用ngx-toggle-switch

安装npm install ngx-toggle-switch --save

用法:-

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

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

在标记语言中:-

<ui-switch></ui-switch>

用于双向绑定

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

Packge文档请参考:-ngx-toggle-switch

【讨论】:

  • 感谢您的解决方案。我不想使用您建议的任何第三方插件或库来实现它。是否可以使用 CSS 或使用 angular4 的引导切换开关来实现??
  • 有什么理由不使用第三方插件或库...?
  • 没有具体原因,但是想尝试用开源bootstrap或者普通css实现
猜你喜欢
  • 2020-10-03
  • 2018-11-04
  • 1970-01-01
  • 2015-03-31
  • 1970-01-01
  • 1970-01-01
  • 2017-07-22
  • 2020-12-01
  • 2020-07-07
相关资源
最近更新 更多