JulioWar / jw-bootstrap-switch-ng2

Bootstrap Switch for Angular 2+
https://juliowar.github.io/jw-bootstrap-switch-ng2/
MIT License
43 stars 14 forks source link

ngModel not updating before onChangeState emits #20

Closed perceptiveml closed 6 years ago

perceptiveml commented 6 years ago

If I bind a variable to ngModel, that value will not get updated before onChangeState callback. Within the callback for onChangeState, event.previousValue and event.currentValue are correct. However, the variable binded to ngModel is not yet updated.

The fix seems to be in directive.ts, setStateValue() function. This will allow angular's ControlValueAccessor registerOnChange() to update ngModel before the onChangeState event is fired.

The fix that worked for me:

private setStateValue(v: boolean): void {
    if (v !== this._innerState) {
        this._onChangeCallback(v);  // Moved above emit

        this.onChangeState.emit({
            previousValue: this._innerState,
            currentValue: v
        });
        this._innerState = v;
    }
}
JulioWar commented 6 years ago

Thanks @perceptiveml for the observation, I am going to do some changes today and I can make the changes.