2017-10-25 5 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> 

私は以下のように提出する形でそれを使用することができます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を追加してこの問題を解決しました。ディレクティブで

は、私が追加しました:

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

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

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

は私の入力構造を更新しました

関連する問題