Angular2 - md-slide-toggle displays the wrong value
You have to find the object property checked value from event . Working Code For Me
Template
<md-card>
<md-slide-toggle
[(ngModel)]="device"
(change)="onChange($event)"></md-slide-toggle>
{{device}}
</md-card>
TS
import {Component} from '@angular/core';
@Component({
selector: 'slide-toggle-overview-example',
templateUrl: './slide-toggle-overview-example.html',
})
export class SlideToggleOverviewExample {
device:number = 1;
onChange(value) {
if (value.checked == true) {
this.device = 1;
console.log(1);
} else {
this.device = 0;
console.log(0);
}
}
}
You're right, not having used the Slide Toggle Component before, it does seem like an odd behavior by default, although this seems to work:
Taken from your Plunker:
Template
<md-card>
<md-slide-toggle
ngDefaultControl
(change)="onChange($event)"
[checked]="device"></md-slide-toggle>
{{device}}
</md-card>
TS
import {Component} from '@angular/core';
@Component({
selector: 'slide-toggle-overview-example',
templateUrl: './slide-toggle-overview-example.html',
})
export class SlideToggleOverviewExample {
device:number = 1;
onChange(e: Event) {
if (e.checked == true) {
this.device = 1;
} else {
this.device = 0;
}
}
}
Working Plunker
At first, I thought it was your use of the ngModel
binding and the click
binding at the same time, but that wasn't the case (since I eventually noticed you were using one-way). It does seem that they get out of sync right from the start when you attempt to assign a numeric value instead of a boolean
.
As this does work as expected as well:
Template
<md-card>
<md-slide-toggle ngDefaultControl
[(ngModel)]="device"></md-slide-toggle>
{{device}}
</md-card>
TS
import {Component} from '@angular/core';
@Component({
selector: 'slide-toggle-overview-example',
templateUrl: './slide-toggle-overview-example.html',
})
export class SlideToggleOverviewExample {
device:boolean = true;
}
Although, it appears that the ng team is aware of at least a version of this issue mentioned in the issue "Slide toggle - (change) event will be fired even when the slider has not change."