Angular ngModel failing to accurately reflect changes in input value

I am facing an issue with implementing a smart number input component that can toggle between allowing or disallowing negative numbers. I have an event listener for the (input) on the <input> element, triggering a function that applies various regex patterns to the value. The function appears to be functioning correctly as the variable's value changes, but the input field value doesn't update (connected to the input via [(ngModel)]).

Below are the code snippets (Angular version 13.2.4):

//number-input.component.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-number-input',
  templateUrl: './number-input.component.html',
  styleUrls: ['./number-input.component.scss']
})
export class NumberInputComponent {
  //basic variables
  @Input() inputValue: string | number | null = null;
  @Input() placeholder: string | number | undefined = undefined;

  //allow negative numbers
  @Input('allow-negative') allowNegative: boolean = false; 

  //emit number onchange
  @Output('app-change') change = new EventEmitter<number>();

  constructor() { }

  onInput() {
    let str = String(this.inputValue);
    console.log(this.inputValue, str);

    // applying regex patterns

    this.inputValue = Number(str);
    console.log(this.inputValue, str);
  }
  onChange() {
    this.change.emit(Number(this.inputValue));
  }
}
<!-- number-input.component.html -->
<input type="text" [(ngModel)]="inputValue" (input)="onInput()" (change)="onChange()">

Cases tested

Input value First console.log Second console.log Outcome
123 '123' '123' 123 '123' No change, as expected
123a '123a' '123a' 123 '123' Input field value doesn't update, but this.inputValue does
-123 '-123' '-123' 123 '123' Input field value doesn't update, but this.inputValue does
123-4 '123-4' '123-4' 123 '123' Input field value doesn't update, but this.inputValue does

In cases where the input field value doesn't update, typing a number seems to trigger the update and display correctly. Typing any other character has no effect.

Any suggestions?

Edit

I found a solution without using ngModel:

The updated onInput() method now takes an event argument to directly modify the input element's value. Here is the working code:

onInput(event: Event) {
  let inputEl = event.target as HTMLInputElement;
  let str = String(inputEl.value);

  // more regex operations

  this.inputValue = Number(str);
  inputEl.value = str;
}

Answer №1

To send your information to the $event parameter, you can follow this example:

<input type="text" [(ngModel)]="inputValue" (input)="onInput($event)" >

In your TypeScript file:

  onInput(event:any) {
    let data = String(event.target.value);
}

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

Showing content based on the route - Angular

I'm struggling to hide the navbar based on a specific route in my application. I have managed to subscribe to the route changes, but I am having difficulty changing the display property accordingly. Here is what I have so far: export class AppCompo ...

Invoke a static method from within a class in Typescript (Angular HttpInterceptor)

Recently, I've been working on an http interceptor that was functioning smoothly until just yesterday. It consists of static methods, and for some reason, one of them is now causing issues. Here is the error message displayed in the console: my.c ...

The yarn/npm package manager seems to be utilizing outdated code in an inexplicable way when paired with mocha and typescript

I recently encountered a strange issue that has left me scratching my head. When I manually run my test command, I receive two test results. However, when I execute the same command in a yarn/npm script, only one result is displayed. Has anyone else experi ...

Angular Universal and WebSockets: A seamless connection

I'm currently facing an issue with incorporating websockets into a server that is utilizing angular universal. It seems like express is intercepting my request before it reaches the sockets, but I could be mistaken. Upon inspecting in chrome, I encou ...

Dynamically manipulate menu items in material-ui and react by adding, removing, editing, or toggling their state

I have scoured every corner of the internet in search of an answer to this dilemma. Imagine a scenario where there is a menu located at the top right of a navigation bar, initially showcasing TWO options (1. Login. 2. Register). When a user clicks on eithe ...

How can you update the property values of a CSS class that already exists in an Angular2+ controller?

In my styles.css file, I have a CSS class called '.users' with a property of color. Now, I am looking to dynamically change the color property value of the 'users' class based on certain conditions in my controller. For instance, I want ...

Deactivate the button in the final <td> of a table generated using a loop

I have three different components [Button, AppTable, Contact]. The button component is called with a v-for loop to iterate through other items. I am trying to disable the button within the last item when there is only one generated. Below is the code for ...

Is there a way to manually trigger a re-render of a component?

I am new to Angular 2 and I'm accustomed to the digest cycle in Angular 1. In Angular 1, when I update the scope of a view, I can manually trigger a digest by calling $scope.$digest(). However, in Angular 2, with its lack of implicit data binding, I&a ...

Having an issue in Angular 2 where the correct function is not triggered when a button is placed within a selectable anchor

Within an anchor element, I have a button that triggers its own click listener for an editing popup module. The anchor itself has another click listener assigned to it. For example: <a (click)="onClick(myId)" class="list-group-item clearfix"> < ...

Error: An unhandled exception occurred during component destruction: TypeError: Cannot access property 'unsubscribe' of undefined

I encountered an issue while trying to unsubscribe during the ngOnDestroy method in my shopping-edit.component.ts file, specifically when clicking on the link to navigate to my recipes page. Here is a screenshot demonstrating the error: error on link clic ...

The issue arises from a custom Angular directive causing a NullInjectorError:StaticInjectorError in the AppModule when trying to inject MatInput into ElementRef

My Angular application is encountering a compilation error after upgrading to Angular 8. Despite updating and reinstalling the Material dependencies, the following error persists: NullInjectorError:StaticInjectorError(AppModule)[MatInput -> ElementRef] ...

Giving the function parameter dynamic type depending on the first parameter

Currently, I have a basic function that my client uses to communicate with my server. In order to maintain flexibility, I have implemented the following: public call(method: string, ...parameters: any[]) {} On the server side, I organize all methods toge ...

Long Waiting Time for the Ionic 2 Splash Screen

I've had struggles with the splash screen while developing several apps using ionic 2. The splash screen seems to take ages to disappear, and I understand that it's influenced by the number of plugins used and their response time. Is there a way ...

Launching Angular 7 on github pages

I am facing an issue with my Angular 7 app that features two routes: the main route and the 'article' route. While the app functions perfectly when tested locally, it fails to load the page's css when deployed on GitHub pages. I followed the ...

Is there a way in typescript to transform empty strings into null values?

As a newcomer to TypeScript, I have been exploring it for some time now. I am working with two interfaces, one is fetching data from a database that I do not have control over and cannot guarantee the values returned are as expected. // Retrieved from the ...

The type of props injected by WithStyles

When working on my class component, I utilize material UI withStyles to inject classes as a property. export default withStyles(styles)(myComponent) In this process, const styles = ( (theme:Theme) => createStyles({className:CSS_PROPERTIES}) I am att ...

What is the best way to connect my Angular 2 project to the "$wakanda" service in order to access and retrieve data efficiently?

Recently, I started a new project on the wakanda.io platform using angular2 and backend technologies. After creating some database entities, I now need to retrieve data from the database on the client side. To do this, I am looking for a way to import the ...

Does the value of an Angular reactive form control only reflect what the user inputs?

I am working with a reactive form where I need to extract values and assign them to a variable defined in an interface. The form is populated using the Google Places API, which disables user interaction with all controls except for the initial address inpu ...

The shop named 'someStore' is currently unavailable! Please ensure that it is being offered by a valid Provider

I'm having trouble setting up a new project using React, Typescript, and MobX. Despite having a relatively simple piece of code, I can't seem to get MobX to work properly. It keeps showing me this error message: Uncaught Error: MobX injector: S ...

The field 'XXX' is not a valid property on the type 'CombinedVueInstance<Vue, {}, {}, {}, Readonly<Record<never, any>>>'

When creating a Vue component with TypeScript, I encountered an error message in the data() and methods() sections: Property 'xxx' does not exist on type 'CombinedVueInstance<Vue, {}, {}, {}, Readonly<Record<never, any>>>& ...