David Pet
David Pet

Reputation: 107

How to add simple onchange events on Angular 2 components

I have the component file and its templateURL html file.

In the html file I have the following code:

 <input type="range" min="0" max="20" value="0" step="1" change="showValue(this.value)" />
    <span id="range">0</span>

In the component, I have this code:

ngAfterviewInit(){
    function showValue(newValue){
        document.getElementById("range").innerHTML=newValue;
    }
}

I put the function in there, but it says its not defined. I am not sure how to define the function, and how to call it in the html file.

Any ideas? Thanks in advance, I'm quite new to A2.

Upvotes: 0

Views: 3419

Answers (2)

Jayakrishnan
Jayakrishnan

Reputation: 4294

You can use ngmodel to bind your value and bind the same to span.No need to define any new functions.Please see below.

 <input type="range" min="0" max="20" [(ngModel)]="variable" step="1"  />
 <span id="range">{{variable}}</span>

you need to declare variable at component side.

Hope it helps!!

Upvotes: 0

Bhupesh
Bhupesh

Reputation: 881

<div ng-app="">
<input type="range" min="0" max="20" value="0" step="1" ng-model="rangenumber" />
<span ng-bind="rangenumber" id="range">0</span>
</div>

Component events Read this article https://toddmotto.com/component-events-event-emitter-output-angular-2

Upvotes: 2

Related Questions