0

I'm trying to implement simple slider range value control in angular 2 app. On stackoverflow I've found this solution

<input type="range" min="0" max="100" #ranger (input)="getMyValue()">

export class MyComponent implements OnInit {
  myValue: number;

  constructor() { }    

   getMyValue() {   
      this.myValue = 2;
   }

  ngOnInit() { }

} 

this always sets control to default state (which is 50). When I simply use html without binding html renders control properly.

<input type="range" min="0" max="100" #ranger value = 2>

What I'm missing here?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
user1765862
  • 13,635
  • 28
  • 115
  • 220

2 Answers2

1

You can just do this,

 <input type="range"  id="range"  min="0" max="100"
    value = "{{getMyValue()}}">

and in TS:

 getMyValue() {   
      return 2;
 }

DEMO

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • Any suggestions, links or docs on how can I track range control change in the view and obviously to update property in the angular 2 controller? – user1765862 Oct 30 '17 at 08:49
1

I would suggest you use a variable with ngModel instead. Calling methods in template means that every time Angular runs change detection, method will be called, so for example this can happen: *ngFor running an infinite loop in angular2 Technically it's not an infinite loop, but method gets called over and over. Especially if you are making http-requests, your browser will crash.

So what I would do:

myValue: number;

ngOnInit() {
  this.myValue = 2;
}

Template:

<input type="range" min="0" max="100" #ranger [(ngModel)]="myValue">
AT82
  • 71,416
  • 24
  • 140
  • 167