Search code examples
htmlangulartypescriptangular9angular10

Calculation of the input values


I am working on a angular app in which I have a matInput field as shown in below code

https://stackblitz.com/edit/ngx-slider-simple-slider-example-dbyxqm?file=src%2Fapp%2Fapp.component.html

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 :

  1. Input is getting appended to 100 it is not doing any addition or substraction
  2. I am not getting immediate output. I am able to display output if I click somewhere outside input field.

How can I resolve above two issues?

HTML

<input matInput (change)="valueUpdated($event)">
my final value is {{myFinalValue}}

TypeScript

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


Solution

  • 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.