2017-10-25 7 views
0

저는 Angular 4 프로젝트에 BootstrapSwitch 라이브러리를 구현하려고합니다.BootstrapSwitchDirective가 Angular4에서 ngModel과 작동하지 않습니다.

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); 
     }); 

    } 
} 

내 입력 구조는 다음과 같습니다 : 내가 함께 결합 할 때,

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

을하지만 :

<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는 다음과 제출 양식을 사용할 수 있습니다 나는 아래 지침을 만들어 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

SwitchDirectiveEventEmitter을 추가하여 문제를 해결했습니다. 이 지침에서

는, 내가 추가 한 :

@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; 
}