Ich versuche BootstrapSwitch Bibliothek in meinem Angular 4-Projekt zu implementieren. Ich habe die unten Richtlinie:BootstrapSwitchDirective arbeitet nicht mit ngModel in Angular4
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);
});
}
}
Meine Eingangsstruktur ist:
<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>
ich es mit Formular verwenden, wie unten einreichen:
<button (click)="submit(switch1.checked, switch2.checked)">Submit</button>
Allerdings, wenn ich versuche, mit zu binden ngModel, es funktioniert nicht.
<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">
Was fehlt, ist ich einen ähnlichen Ansatz erraten, wie unten in AngularJS:
element.on('switchChange.bootstrapSwitch', function(event, state) {
if (ngModel) {
scope.$apply(function() {
ngModel.$setViewValue(state);
});
}
});
Jede Hilfe sehr geschätzt wird.