Controlling the upper and lower limits in an input field for numerical values while manually typing in the text

Trying to implement an Angular component input with number type that allows setting a maximum and minimum value.

Here is the code snippet used for calling the component in HTML:

<app-input-number [(value)]="inputMinMaxValueNumber" [min]="min" [max]="max"></app-input-number>

Below is the HTML code snippet for the actual component:

<input class="gh-input" type="number" [max]="max" [min]="min" [name]="name"  
[readonly]="readonly" [disabled]="disabled" [ngClass]="disabled ? 'disabled' : ''" [value]="value" />

And here's the TypeScript logic for the component:

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-input-number',
  templateUrl: './input-number.component.html',
  styleUrls: ['./input-number.component.scss']
})
export class InputNumberComponent implements OnInit {

  @Input() name: String;
  @Input() readonly: Boolean;
  @Input() disabled: Boolean;
  @Input() max: number;
  @Input() min: number;
  currentValue: number;

  @Output()
  valueChange = new EventEmitter<number>();

  @Input()
  get value() {
    return this.currentValue;
  }

  set value(val) {
    if (val > this.max) {
      this.currentValue = this.max;
    } else if (val < this.min) {
      this.currentValue = this.min;
    } else {
      this.currentValue = val;
    }

    this.valueChange.emit(this.currentValue);
  }

  constructor(private translateService: TranslateService) { }

  ngOnInit() {
  }
}

Facing an issue where manually entering a value exceeding the max limit works initially but fails to restrict the value afterward (works fine for the min).

Appreciate any assistance provided.

Answer №1

The functionality may not be successful as you are unable to establish a two-way connection with the value property within an input element. It is recommended to utilize ngModel as an alternative.

Nevertheless, relying on ngModel, or any type of two-way binding, is deemed less effective. Opt for FormGroups integrated with personalized validators instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Get a file transfer from MVC 5 to Angular 2

After gaining experience in C# backend and ASP.Net MVC, I decided to take on the challenge of learning Angular 2. While most of the experience has been positive, I have hit a roadblock with a simple file download task. Despite studying various examples on ...

Can the month dropdown in react-datepicker be modified to display numbers instead of names?

Here is the code I have: <DatePicker selected={value?.toDate()} onChange={(date) => this.handleMonthChange(date)} inline showMonthYearPicker dateFormat={this.props.formatString} /> https://i.sstatic.net/SkdGP.png I am seeking ...

How can one effectively monitor the advancement of a file transfer operation?

Looking at integrating a Spring Boot REST API with an Angular Frontend, I am interested in monitoring file upload/download progress. I recently came across an informative article that dives into the implementation details of this feature. The approach see ...

When working with Angular, the onSubmit method may sometimes encounter an error stating "get(...).value.split is not a function" specifically when dealing with Form

When the onSubmit method is called in edit, there is an error that says "get(...).value.split is not a function" in Form. // Code for Form's onSubmit() method onSubmitRecipe(f: FormGroup) { // Convert string of ingredients to string[] by ', ...

Angular2 - Model not being refreshed by Directive

I have implemented a directive on an HTML input box to handle numeric values. The directive is meant to "clean" the number (removing commas, dollar signs, etc) when a user pastes a number into the textbox. Although the cleaning code works properly, the iss ...

Using Typescript to Define Mongoose Schemas

Currently exploring the creation of a user schema in TypeScript. I've observed that many people use an interface which functions well until I introduce a message involving username.unique or required property. No error code present: import {model, mo ...

How to toggle visibility of multiple div elements in ReactJS

When working in react-js, I encountered a situation where two div elements and two buttons were used. Clicking the first button displayed the first div and hid the second div. Conversely, clicking the second button showed the second div and hid the first d ...

Incorporating D3.js into Angular 6 for interactive click events

Currently working on building a visual representation of a tree/hierarchy data structure using d3.js v4 within an Angular environment. I've taken inspiration from this particular implementation https://bl.ocks.org/d3noob/43a860bc0024792f8803bba8ca0d5e ...

The references to the differential loading script in index.html vary between running ng serve versus ng build

After the upgrade to Angular 8, I encountered a problem where ng build was generating an index.html file that supported differential loading. However, when using ng serve, it produced a different index.html with references to only some 'es5' scri ...

The Google Books API has reached its limit for requests

Encountering a rate limit exceeded error from the Google Books API while using this demo: To reproduce, open the developer console in Chrome and perform some searches. The rate limit errors will be displayed in the console. [],"lazyUpdate":null},"status" ...

Using Angular 2: A Beginner's Guide to Navigating with the Latest Angular 2.0.0-rc.1 Router

As I embarked on a new Angular 2 project, I was puzzled to discover that I inadvertently installed two different versions of the angular router: "@angular/router": "2.0.0-rc.1", "@angular/router-deprecated": "2.0.0-rc.1", Despite my best efforts, I co ...

The functionality of Ng update is failing to operate properly on outdated node versions

Currently in the process of upgrading from angular 7 to 15 for my project. Taking it step by step, but I'm facing the challenge of having to do it manually since my ng update isn't working under any circumstances. The error message states that my ...

How can I set the default bindLabel for a dropdown in @ng-select/ng-select when the self change event occurs in Angular

I have a scenario where I need to set the default value to null in the ng-select. If the user selects an option from the dropdown first, then on the change event it should check if the Amount model is not null or blank. If the Amount model is blank, then ...

How can elements be collapsed into an array using the Reactive approach?

Consider this TypeScript/Angular 2 code snippet: query(): Rx.Observable<any> { return Observable.create((o) => { var refinedPosts = new Array<RefinedPost>(); const observable = this.server.get('http://localhost/ra ...

Having trouble executing Angular e2e tests above version 2 with protractor while using a proxy

Seeking assistance and guidance! Operating on a Windows system Globally installed Protractor Version 5.3.0 Ran webdriver-manager clean before updating webdriver Updated version with the following command: webdriver-manager update --ie32 --proxy ...

Building upon the foundation: Extending a base component in Angular

I have a Base Component that is extended by its children in Angular. However, when creating a new Component using angular-cli, it generates html and css files that I do not need for the base component. Is there a way to create a Base Component without inc ...

Is it possible to specify broad keys of a defined object in TypeScript using TypeScript's typing system?

const obj: {[key: string]: string} = {foo: 'x', bar: 'y'}; type ObjType = keyof typeof obj; Is there a way to restrict ObjType to only accept values "foo" or "bar" without changing the type of obj? ...

CDNify load error causing Grunt Serve to fail

I have encountered an issue with a freshly installed Angular project. When I try to run the grunt serve command, I receive the following error: I am currently using Node 12.6.1 with Source Tree and have confirmed that Bower is properly installed. Loading ...

Error: The function jquery_1.default is not recognized by webpack

I am encountering an issue with using external imports of jQuery in webpack. Despite trying different import syntaxes such as import $ from 'jquery', import * as $ from 'jquery, and const $ = require('jquery'), I continue to receiv ...

Your search parameter is not formatted correctly

I am currently working on filtering a collection based on different fields such as name by extracting the values from the URL parameters. For example: http://localhost:3000/patient?filter=name:jack I have implemented a method to retrieve and convert these ...