I'm trying to implement BootstrapSwitch library into my Angular 4 project. I created the below directive:
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);
});
}
}
My input structure is:
<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>
I can use it with form submit as below:
<button (click)="submit(switch1.checked, switch2.checked)">Submit</button>
However, when I try to bind with ngModel, it is not working.
<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">
What missing is I guess a similar approach as below in angularjs:
element.on('switchChange.bootstrapSwitch', function(event, state) {
if (ngModel) {
scope.$apply(function() {
ngModel.$setViewValue(state);
});
}
});
Any help is appreciated.
I have solved the problem by adding an EventEmitter
into my SwitchDirective
.
In the directive, I have added:
@Output() switch = new EventEmitter<any>();
ngAfterViewInit() {
this.directive.on('switchChange.bootstrapSwitch', function (event, state){
if(fnc.observers.length)
fnc.emit(state);
});
}
Updated my input structure:
<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">
Added related function to my component:
updateModel(model: Model, state: boolean){
model.attribute = state;
}