Update the ngModel value once input validation has been successfully validated

My input is defined as shown below

    <input
      id="xInputControl"
      name="xInputControl"
      type="text"
      xInput
      class="form-control"
      [(ngModel)]="x"
      #validated="ngModel"
      (ngModelChange)="valueChanged()"
    />

I have implemented a custom validator for the input field

@Directive({
  selector: '[xInput]',
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: LatestXInputValidatorDirective,
      multi: true,
    },
  ],
})
export class LatestXInputValidatorDirective implements Validator {

  validate(control: AbstractControl): ValidationErrors | null {
    if (
      control.value === undefined ||
      control.value === null ||
      control.value === ''
    ) {
      return { emptyInput: 'dummy text' };
    } else if (
      control.value.indexOf(',') > 0 ||
      control.value.indexOf('.') > 0
    ) {
      return { decimalNumber: control.value };
    } else {
      const parsed = parseInt(control.value);
      if (isNaN(parsed)) return { notANumber: control.value };
      else if (parsed > 200) return { overLimits: control.value };
      else if (parsed < 1) return { negativeNumber: control.value };
      else if (parsed === 1) return { useLatestAggregation: control.value };
      // The value is valid
      else return null;
    }
  }
}

Referencing this documentation

The ngModel will be set only when input validation passes. For example, email inputs must follow the format user@domain

Also read more on this page

By default, ngModel sets the model value to undefined for invalid input values.

I expect the ngModelChange method in the HTML input to be called only when the input has a valid value that passes the LatestXInputValidatorDirective validation.

Unfortunately, this is not happening. The

(ngModelChange)="valueChanged()
function is triggered after every keystroke. I can verify this through the following method

  valueChanged() {
    console.warn('The current value of x is ', this.x);
    ...
  }

I see logs appearing in the console with each keystroke

How can I ensure that valueChanged is only invoked when the input contains a VALID value that clears the validation from LatestXInputValidatorDirective?

Answer №1

If you're looking for a different approach, I would recommend avoiding the dual binding method. When using the two-way binding with [()] syntax (also referred to as 'banana-box syntax'), the value in the user interface constantly synchronizes back to a domain model within your class.

[(ngModel)]="x"

To implement this, your HTML code could resemble the following:

<form #it="ngForm" (ngSubmit)="submit(it, $event)">
  <input
  type="text"
  id="xInputControl"
  name="xInputControl"
  class="form-control"
  ngModel
  #xInputControl="ngModel"
  xInput/>

  <button type="submit" [disabled]="!it.valid">
   submit
  </button>
</form>

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

Service error: The function of "method" is not valid

In one of my Angular 2 applications, I have a class that contains numerous methods for managing authentication. One particular method is responsible for handling errors thrown by the angular/http module. For example, if a response returns a status code o ...

What is the best way to display input data (with names and values) in a textarea field

I'm currently working on a project that requires the value of a textarea to be updated whenever one of the input values in the same form is changed. Here is the HTML code: <form id="form" action="" method=""> <textarea readonly class="overv ...

Unlocking the Power of ReactJS: Passing Values in Material UI for Advanced JSON Structures

How can I access complex objects in the GRID component of material UI? Specifically, I am trying to access the ami_info.account, but it only displays Undefined in the UI. var columns = [ { field: 'id', headerName: 'ID', width: 90, ...

Implement a transformation on the API endpoint's JSON data to prepare it for display in a React

I'm currently developing a React application and have created a component to display tabular data. The API endpoint I am calling returns data in the following format: { "bitcoin": { "usd": 48904, "usd_market_cap": 9252 ...

Having trouble editing a form with React Hooks and Redux?

Seeking assistance with creating an edit form in React that utilizes data stored in Redux. The current form I have created is displaying the values correctly, but it appears to be read-only as no changes are being reflected when input is altered. Any advic ...

gmap3 has encountered an error: undefined is not a valid function

I am working on a WordPress site and trying to integrate a Google map into the contact page. However, I'm encountering an error Uncaught TypeError: undefined is not a function in the JavaScript console. Below is the code snippet causing the issue, can ...

Tips for managing and capturing errors in Express

const database = require('database'); const express = require('express'); const app = express(); const cors = require('cors'); app.use(cors()); const bodyParser = require('body-parser'); const urlencodedParser = body ...

Why does the control skip the onreadystatechange function for the ajax object?

Just beginning my journey into web-development. Recently, I encountered an issue with a signup page I created that involves asynchronous calls to php. Upon debugging, I noticed that the onreadystatechange function is being completely skipped over. Any assi ...

Is there a way to modify the displayed value of json_encode() with jQuery?

I am using the json_encode() function to insert data into the database. How can I retrieve just the values of name_units from the units row in the database? This is how the output looks like in PHP code (generated by json_encode()): my_table=>units=>nam ...

Utilizing the Django object array in AngularJS – a comprehensive guide

I have a Django variable structured like this: [<Topic object>, <Topic object>] When passing it to Angular using ng-init, I wrote the following: <div class="profile-navigation" ng-init="ProfileTopics={{ProfileTopics|safe}} "> However, ...

Our system has picked up on the fact that your website is failing to verify reCAPTCHA solutions using Google reCAPTCHA V2

Error Message We have noticed that your website is not validating reCAPTCHA solutions. This validation is necessary for the correct functioning of reCAPTCHA on your site. Please refer to our developer site for further information. I have implemented the re ...

Assistance Required for Making a Delicious Cookie

Within my interface, there are two buttons displayed - one is labeled yes while the other is called no. <input type="button" name="yes" onclick="button()"> <input type="button" name="no"> In order to enhance user experience, I am looking to i ...

How to achieve the functionality of multiple inheritance using Object.create()

Seeking insights on implementing multiple inheritance in JavaScript. Various methods exist, each with pros and cons. However, there lacks a comprehensive analysis of Object.create() presented in an understandable manner. After conducting experiments, I hav ...

Rapidly verifying PHP arrays with jQuery/AJAX

I am looking for a way to validate values within a PHP array in real-time without the need to click a submit button by utilizing jQuery/AJAX. As users type an abbreviation into a text field, I want to instantly display whether the brand exists (either v ...

Problems with WordPress Theme Rendering in Outdated Versions of Internet Explorer

Currently, I am developing a website for Chase on the Lake at http://chaseonthelake.com/. While everything looks perfect in FireFox, there are some display issues when viewing it in Internet Explorer. The dropdown transparency is not showing correctly, m ...

A guide to fetching a JSON Object from a URL using Node.js and Express

As a newcomer to Node.js and Express, I am venturing into my first real project with these technologies. In this simple Node.js/Express project, my goal is to retrieve a JSON object from a URL. Additionally, I plan to create another URL that shows HTML co ...

The appropriate method for transferring a prototype to an object

From my perspective, prototypes work like this: let Animal = function() { this.bark = "woof"; } Animal.prototype.barkLoud = function() { return this.bark.toUpperCase(); } let x = new Animal(); x.barkLoud() = "WOOF"; I f ...

Developing a React Native app using Expo and Firebase? Learn how to prevent Firebase details from

I have encountered a problem with my code while working on the user edit profile page in my react native app. The issue I am facing is related to displaying the previously inputted firebase details from the collection in the text input fields when the user ...

Transform a div's style when hovering over another div using absolute positioning without repetition

I am facing an issue with multiple divs positioned absolutely on top of a primary div with relative positioning. I want one specific div to change its background-color when hovering over another div within the same parent div. Though I know about ad ...

Having trouble with innerHTML.value functionality?

Recently, I've been delving into creating a JavaScript program that fetches Wikipedia search results. Initially, everything seemed to be working fine as I was able to display the searched item using the alert() method. However, for some reason, it now ...