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

What could be causing the consistent Mocha "timeout error" I keep encountering? Additionally, why does Node keep prompting me to resolve my promise?

I'm encountering a timeout error repeatedly, even though I have called done(). const mocha = require('mocha'); const assert = require('assert'); const Student = require('../models/student.js'); describe('CRUD Tes ...

The Art of Div Switching: Unveiling the Strategies

I have a question regarding my website. I have been working on it for some time now, but I have encountered a challenge that I am struggling to overcome. After much consideration, I am unsure of the best approach to take. The issue at hand is that I have ...

Information vanishes as the element undergoes modifications

I am currently working with a JSON file that contains information about various events, which I am displaying on a calendar. Whenever an event is scheduled for a particular day, I dynamically add a div element to indicate the presence of an event on the c ...

Implementing promises in my MEAN stack application

I have developed a controller that performs a Bing search based on the user's input in the URL. After testing the controller with console.log, it seems to be functioning correctly and I have set the variable to return the results. However, when trying ...

Error Encountered: Unable to utilize $(...).mask function with jQuery in ASP.NET using C#

I have encountered an issue while working on a task involving jQuery masked for date. When running the task in HTML, it works perfectly fine. However, when attempting to run it in ASP.NET, I face the problem where 'mask is not a function'. Below ...

Unexpected Disconnection of AJAX Response Moments Before Rebooting the Raspberry Pi

I currently have a LAMP server set up on my Raspberry Pi 4, where a web page is utilizing an AJAX call to trigger a php script that initiates a reboot of the pi. The php script echoes a JSON string response back to the web page indicating that it is prepar ...

Error: TypeScript Knockout table failing to display data

I have a table that displays invoices, along with a nested table showing the individual checks associated with each invoice. I am using knockout and typescript to render these tables. Currently, I can successfully display the invoices but am facing difficu ...

Design a customizable input field to collect HTML/JS tags

I'm looking to incorporate a similar design element on my website. Can anyone offer me some guidance? Check out the image here ...

The "Read more" feature is not functional on mobile devices

I am encountering issues with my Wordpress blog on mobile screens. The "read more" button is not functioning, and the screen size does not fit properly on mobile devices. Visit abood250.com for more information. CSS Styling: /* =Global ----------------- ...

What is the best way to integrate JQuery URL in Joomla components?

Can anyone show me how to load a jquery URL in Joomla (Component)? I have a button that, when clicked, will reload the page and use the GET method to display a value from a variable. JavaScript: jQuery("#btnclickme").click(function(){ jQuery("#divpro").l ...

Python code allowing users to navigate back to the previous page while retaining elements

After my script scrapes the page, it automatically clicks a button if a new element meeting certain criteria is found. Everything works perfectly when there is only one element, but an issue arises when the button click leads to a new page opening. If ther ...

The lightbox is triggered by clicking on a different div to display its content

Great news - my lightbox is up and running! Each image on my website corresponds to a different organization, and clicking on the image opens a specific lightbox. My question is: how can I have a lightbox configured so that only the trigger image is displ ...

What is the best way to import an external file from the project's root directory using webpack?

I am currently working on a unique npm package that will allow for the integration of custom rules from the project root. This functionality is similar to how prettier searches for a .prettierrc file in the project root. For this particular package, I am ...

What is causing the VueJS template ref to be undefined when dealing with multiple divs

I have been working on a simple Vue component and I am trying to access the DOM element from the template. The initial component works perfectly: <template> <div ref="cool">COOL!</div> </template> <script> export ...

Tap here to switch between 2 jquery functions

Due to the deprecation of the toggle() method in jQuery version 1.8 and its removal in version 1.9, an alternative approach is needed for versions 1.11 and above. You can check out the documentation for more information. If you are looking to replicate th ...

Two separate projects targeting Admin and User interfaces versus a unified application featuring distinct themes for each user role

In React, there is a scenario that needs to be implemented. An admin panel with various functionalities like Auth, charts, analytics, and user management has already been pre-built. The goal now is to connect this admin panel to another website as the back ...

Toggle between the Angular test/development module and the production module

Currently, I am working on implementing an Angular app. During my e2e tests, I encountered a need to mock some server requests while allowing others to pass through using e2e httpBackend. Vijitta has provided an example of how to utilize the HttpBackend: ...

Setting up a Bootstrap tokenfield for usage with a textarea

I was attempting to set up a tokenfield on a textarea with increased height, but it is showing up as a single-line textbox. How can I modify the tokenfield to function properly with a textarea? <textarea name="f1_email" placeholder="Enter Friends' ...

Utilizing React.hydrate in conjunction with Vue: A Beginner's Guide

Wondering about a unique scenario here - I have a website built with Vue and now I aim to showcase a library I developed in React. In order to steer clear of server-side rendering (SSR), I can simply wrap ReactDOM.hydrate(ReactApp, document.getElementById( ...

Is it recommended for synchronous code invoked by a Promise's .then method to generate a fresh Promise

I recently wrote some code containing a mix of asynchronous and synchronous functions. Here's an example: function handleAsyncData() { asyncFunction() .then(syncTask) .catch(error); } After some research, I learned that the then method is ...