BootstrapSwitchDirective не работает с ngModel в Angular4

Я пытаюсь внедрить библиотеку 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 ответ

Решение

Я решил проблему, добавив 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;
}
Другие вопросы по тегам