BootstrapSwitchDirective无法在Angular4

时间:2017-10-25 08:02:15

标签: angular angular-directive bootstrap-switch

我正在尝试将BootstrapSwitch库实现到我的Angular 4项目中。我创建了以下指令:

import {Directive, ElementRef, Input, AfterViewInit} from '@angular/core';

@Directive({ selector: '[switch]' })
export class SwitchDirective implements AfterViewInit {
    @Input() onText: string;
    @Input() offText: string;
    @Input() labelText: string;

    directive: any;

    constructor(el: ElementRef) {
        this.directive = $(el.nativeElement);

        $.fn.bootstrapSwitch.defaults.onColor = 'success';
    }

    ngAfterViewInit() {
        var options = {
            onText: this.onText,
            offText: this.offText,
            labelText: this.labelText,
        };

        this.directive.bootstrapSwitch(options);

        this.directive.on('switch-change', function () {
            this.directive.bootstrapSwitch('toggleRadioState');
        });

        this.directive.on('switch-change', function () {
            this.directive.bootstrapSwitch('toggleRadioStateAllowUncheck');
        });

        this.directive.on('switch-change', function () {
            this.directive.bootstrapSwitch('toggleRadioStateAllowUncheck', false);
        });

    }
}

我的输入结构是:

<input type="checkbox" class="make-switch" onText="Y" offText="N" labelText="Switch 1" switch #switch1>
<input type="checkbox" class="make-switch" onText="Y" offText="N" labelText="Switch 2" switch #switch2>

我可以使用表单提交,如下所示:

<button (click)="submit(switch1.checked, switch2.checked)">Submit</button>

但是,当我尝试与ngModel绑定时,它无法正常工作。

<input type="checkbox" class="make-switch" onText="Y" offText="N" labelText="Switch 1" switch [(ngModel)]="selectedItem.switch1" name="switch1" [checked]="selectedItem.switch1== 1">
<input type="checkbox" class="make-switch" onText="Y" offText="N" labelText="Switch 2" switch [(ngModel)]="selectedItem.switch2" name="switch2" [checked]="selectedItem.switch2 == 1">

缺少的是我想在angularjs中采用类似的方法:

element.on('switchChange.bootstrapSwitch', function(event, state) {
    if (ngModel) {
        scope.$apply(function() {
            ngModel.$setViewValue(state);
        });
    }
});

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我通过在EventEmitter添加SwitchDirective来解决了这个问题。

在指令中,我添加了:

@Output() switch = new EventEmitter<any>();

ngAfterViewInit() {
    this.directive.on('switchChange.bootstrapSwitch', function (event, state){
        if(fnc.observers.length)
            fnc.emit(state);
    });
}

更新了我的输入结构:

<input type="checkbox" class="make-switch" onText="Y" offText="N" labelText="Switch 1" (switch)="updateModel(model, $event)" [(ngModel)]="selectedItem.switch1" name="switch1" [checked]="selectedItem.switch1== 1">

为我的组件添加了相关功能:

updateModel(model: Model, state: boolean){
    model.attribute = state;
}