Angular2 - md-slide-toggle displays wrong value

My problem is that the md-slide-toggle value has the correct value, but it does not display correctly.

For example:

At the beginning, the value is 1, and the switch is active.

  • Time taken to press the switch: the value is 0, but the switch is still active.

  • Switch Press Time: The value is 1, but now the switch is now inactive.

  • ...

Have a look here: https://plnkr.co/edit/kxehpwaat5dezNActZbn?p=preview

//. HTML

<md-card> <md-slide-toggle ngDefaultControl (click)="onClick()" [ngModel]="(device)"></md-slide-toggle> {{device}} </md-card> 

//. Ts

 device:number = 1; onClick() { let tmp; if (this.device == 1){ tmp=0; } if (this.device == 0){ tmp=1; } this.device=tmp; } } 
+7
javascript html angular material-design angular-material2
source share
2 answers

You're right, but you didn’t use the “Slide Component” , this seems like a weird default behavior, although it 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 you used the ngModel binding and click binding at the same time, but that was not the case (since I eventually noticed that you are using unidirectional). They seem to go out of sync right from the start when you try to assign a numerical value instead of boolean .

Since this works the same as expected:

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

Despite the fact that the ng team knows at least the version of this problem mentioned in the release, “ Slide Switching Event - (Change) will be, even if the slider has not changed.

+7
source share

You must determine the value of the property of the object from the 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); } } } 
+3
source share

All Articles