Angular's AsyncValidatorFn is triggered by the onblur event and does not work with keypress events

I'm currently working with the latest version of Angular and I'm attempting to implement a custom validation for checking a code through a RestAPI. The example below is functional, but it doesn't trigger on keypress events; it only activates onblur. The text "Code not available" only appears when the input field loses focus. Any suggestions?

Thank you in advance for your assistance!

This is the formbuilder

this.form = this.formBuilder.group({
      code: ['',
        [Validators.required, Validators.pattern('^[A-Za-z0-9]{4}')],
        this.asyncCodeValidator.validate(),
      ]
    });

This is the asyncCodeValidator service

@Injectable({ providedIn: 'root' })
export class AsyncCodeValidatorService {
  constructor(private codeService: CampaignService) {}

  validate(): AsyncValidatorFn {
    return (control: AbstractControl): Observable<ValidationErrors | null> => {
      return this.searchCode(control.value).pipe(
        map(result => {
          return result.available ? null : { notUnique: 'Action code not unique' };
        })
      );
    };
  }

  searcCode(code: string): Observable<CodeValidate> {
    return timer(500).pipe(
      switchMap(() => {
        return this.codeService.validateCode(code); // return Observable<CodeValidate> 
      })
    );
  }
}

This is the html control

<form [formGroup]="form">
       <input type="text" formControlName="code">

      <p style="color: red" *ngIf="form.get('code').errors?.notUnique">code not available</p>
</form>

Using

    "@angular/common": "11.2.12",
    "@angular/compiler": "11.2.12",
    "@angular/core": "11.2.12",
    "@angular/forms": "11.2.12",
    "@angular/material": "11.2.12",

Answer №1

I have identified the resolution to the issue, it was related to the changeStrategy.OnPush setting of the component

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

Executing functions in a loop using Angular

Within my component, there is a foreach loop triggered when a client is selected. Inside this loop, I need to execute a function within the same component. The issue arises with calling the function using `this.functionName()` because 'this' no ...

The improved approach to implementing guards in Angular

I am currently looking for the most effective way to utilize Angular "guards" to determine if a user is logged in. Currently, I am checking if the token is stored. However, I am wondering if it would be better to create an endpoint in my API that can verif ...

Tips for Resolving TypeScript Error 7053 when using the handleChange function in a React Form

Seeking assistance with creating a versatile handleChange function for a React form. The goal is for the handleChange function to update the state value whenever a form field is modified, while also accommodating nested values. Below is my attempt: const ...

JavaScript Equivalent of Declaration in TypeScript

In my Next JS application, I encountered a situation where a line of code relies on a variable from a script src in the app.tsx page. Here's how it looks: app.tsx: <script src="https://js.stripe.com/v3/"></script> config.ts: de ...

Implement Stripe API mocking using Jest in Node.js with Typescript

I'm having trouble simulating the Stripe API for testing purposes. Although I don't have much experience with mocking functions using jest, I've already extensively researched how to mock the Stripe API without success. My file structure is ...

What is the best strategy for managing a sizable react application using react-query?

Since diving into React with functional components and react-query, I've been facing some confusion on how to properly organize my components. Typically, I design components by having a top-level component handle all data access and pass data down to ...

Typescript classes fail to adhere to interface types

interface IFoo { method: (ha: string) => void; } class Foo implements IFoo { public method(ha) {} } The message displayed when hovering over the 'ha' parameter in the class method reads: Parameter 'ha' implicitly has an &apo ...

webpack - compile one TypeScript file separately (2 actions)

In summary... When my Vue files are combined with background.ts, webpack processes them to create bundled vue files along with background.js I'm unable to run the background.js script I expected background.js to only contain "console.log(' ...

Displaying an element in Angular 2 based on the selected option value

Looking for the most efficient method to display an element based on a selection from a dropdown menu in Angular 2. Despite trying various techniques, I have been unsuccessful in achieving the desired outcome! Below is the current implementation: HTML: ...

What is the best way to determine if an object.property is defined in Angular 2?

Is there a similar function in Angular 2 to angular.isDefined from Angular 1? I have tried using the safe navigation operator ?., which is only supported in templates. ...

Encountering the NullInjectorError: No provider for Injector! error repeatedly while attempting to interact with a store

I've been working on a web app that incorporates a store by following this tutorial: . However, I keep encountering the following error: main.ts:13 NullInjectorError: StaticInjectorError(AppModule)[InjectionToken @ngrx/store Initial Reducers -> In ...

Navigating through nested Firebase realtime DB queries using await/async techniques

In the process of developing a Firebase function (Gist), I encountered a challenge that I'm seeking assistance for. The function starts by querying a realtime database reference (events) using this code: await admin.database().ref('/events_geo ...

There was an issue with the specified entry-point "auth0/angular-jwt" as it is missing required dependencies

I am currently working on an Angular project with the following versions: @angular-devkit/architect 0.901.1 @angular-devkit/core 9.1.1 @angular-devkit/schematics 9.1.1 @schematics/angular 9.1.1 @schematics/update 0.901.1 rx ...

I'm having trouble importing sqlite3 and knex-js into my Electron React application

Whenever I try to import sqlite3 to test my database connection, I encounter an error. Upon inspecting the development tools, I came across the following error message: Uncaught ReferenceError: require is not defined at Object.path (external "path ...

What causes the discrepancy in errors when dealing with subtype versus regular assignments?

Below is a sample code that has been checked by TypeScript playground https://www.typescriptlang.org/play/ interface PartialCustomData { option?: number; } interface A { [key: string]: string | PartialCustomData; } interface B extends A { [k ...

How can you automate the execution of unit tests in Angular before pushing changes to Git?

There have been instances in Angular projects where the unit tests are triggered every time a build is carried out, as well as when running the git push command. In case any tests fail during either of these commands, the process halts until all unit tes ...

The data type 'string | boolean | null' cannot be assigned to type 'boolean'. Specifically, the type 'null' cannot be assigned to type 'boolean'

Can you spot the issue in this code snippet? isAuthenticated(): boolean { var token = localStorage.getItem(ACCESS_TOKEN_KEY); return token && !this.jwtHelper.isTokenExpired(token); } Error: The variable is returning a type of 'string | bo ...

The parameter type 'router' cannot be replaced with the type 'typeof ...'. The 'param' property is not included in the type 'typeof'

I'm currently working on a node application using TypeScript and have set up routing in a separate file named 'route.ts' import home = require('../controller/homeController'); import express = require('express'); let ro ...

Utilizing the JavaScript Array.find() method to ensure accurate arithmetic calculations within an array of objects

I have a simple commission calculation method that I need help with. I am trying to use the Array.find method to return the calculated result from the percents array. The issue arises when I input a price of 30, as it calculates based on the previous objec ...

Encountering difficulty with retrieving information from a shared service on Angular 6

Attempting to pass JSON data from one component to another component (like parent to child) using a service. The service has two methods: setJsonData and getJsonData. Service Class import { Injectable } from '@angular/core'; @Injectable({ pr ...