I am working on a angular app in which I have a matInput field as shown in below code
User can enter positive or negative value. Suppose I have current value as 100 and user enter +5 or 5(user can use + symbol or can give positive number) I want my final output as 100 and if user enter -5 then I want my final output should be 95 and I want to display output immediately on screen. The problem I am facing with my code is :
How can I resolve above two issues?
<input matInput (change)="valueUpdated($event)">
my final value is {{myFinalValue}}
import { Component } from '@angular/core';
import { Options } from 'ng5-slider';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
public myFinalValue: number;
valueUpdated(event) {
this.myFinalValue = 100 + event.target.value;
}
}
the input element returns the value as a string instead of a number.
You need to convert event.target.value
to a number before adding the two.
You can use the shorthand +event.target.value
, which will convert the value to a number (it's equivalent to parseInt(<var>)
)
valueUpdated(event) {
this.myFinalValue = 100 + +event.target.value;
}
if you want the UI to update on every input change, you need to use the (input)
event instead of the (change)
event:
<input matInput (input)="valueUpdated($event)">
my final value is {{myFinalValue}}
Here's my fork of your stackblitz with the changes.