0

I am trying to bind "oninput" event of input range element to a custom method declared in respective typescript file.

Following is the HTML element:

<input type="range" id='motivation-grade' value="3" min="1" max="5">

This is the event listener code which I am using in ngOnInit method of my angular2 component:

  ngOnInit() {
    this.elem = document.getElementById('motivation-grade');
    this.elem.addEventListener("click", this.motivation(document.getElementById('motivation-grade').value));
  }

Here in motivation(str:string) method, I want to show some links based on selected value every time user changes it. But motivation() method is firing only once in starting and after that it is not seemed to be hit. Can somebody help me to understand what I am missing?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jayant Pareek
  • 360
  • 3
  • 18

2 Answers2

0

I am guessing you are using Angular2. If you want to trigger an event on input click you can do something like this.

<input type="range" id='motivation-grade' (click)="onInputClick(3)" value="3" min="1" max="5">

Your component Typescript file can include this.

public onInputClick(value){
  //do something ...
}

Try avoiding direct DOM manipulation in Angular 2. It's a bad practice

Rudraprasad Das
  • 348
  • 1
  • 10
  • Thanks Rudra, however I am getting 'undefined' when trying to access the value using your way. Any suggestions ? – Jayant Pareek Jan 12 '17 at 18:21
  • @Jayant You need to pass in the actual value when you are using (click) on input. It can either be a variable or the actual value you want to pass in this case (click) = "onInptClick(3)" – Rudraprasad Das Jan 12 '17 at 18:38
  • But then it completely ends the purpose of this function, right? I need the updated value every time user changes it. By the way, I resolved the issue by using var self = this in my ngOnInit and then using it in my addEventListener function. Thanks for the help. – Jayant Pareek Jan 13 '17 at 05:47
0

Avoid direct dom manipulation. Like Rudraprasad suggested use
<input type="range" id='motivation-grade' (click)="onInputClick($event)" value="3" min="1" max="5">
you can print the event using
onInputClick(event):void{ console.log(event); } most likely your desired value will be stored in event.target.value