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

Error: Observable<any> cannot be converted to type Observable<number> due to a piping issue

What causes the type error to be thrown when using interval(500) in the code snippet below? const source = timer(0, 5000); const example = source.pipe(switchMap(() => interval(500))); const subscribe = example.subscribe(val => console.log(val)); V ...

What steps do I need to take for the function to accurately determine the return type?

class Foo { name: string; constructor({name}: {name: string}) { this.name = name; } } class Bar<T extends Foo> { foo: T; constructor({foo}: {foo: T}) { this.foo = foo; } } class CustomFoo extends Foo { xxx: string; constr ...

Tips and tricks for setting up a functional react select component using Material UI

Having an issue with React Select material UI where the dropdown select is not functioning properly. The popup does not open up as expected. I am looking to display react select in a modal dialog box. import MenuItem from "@mui/material/MenuItem" ...

How do I get rid of an unwanted and vulnerable dependency that NPM installed without my consent?

I have come across a vulnerability in my docker image related to a package that I wish to remove. The problematic package can be found at: Upon navigating through the node_modules folder starting from app/node_modules/resolve/test/resolver/multirepo/pac ...

Difficulties with managing button events in a Vue project

Just getting started with Vue and I'm trying to set up a simple callback function for button clicks. The callback is working, but the name of the button that was clicked keeps showing as "undefined." Here's my HTML code: <button class="w ...

Combine form data from a reactive form into a string using interpolation

Currently, I am working with an object that has a string property embedded within it. The string in this property contains interpolation elements. For my user interface, I have implemented a reactive form with an input field. My goal is to display the ent ...

Discover the power of merging multiple events in RxJS for efficient data retrieval and filtering

In various scenarios, I need to display a table of data with additional functionality for filtering and refreshing. The table is accompanied by two input fields - one for local filtering (searchLocal) and another for backend filtering (searchBackend). Ther ...

The marker is not updating in real-time with the actual latitude and longitude on the Google Maps angular

I have been attempting to update the marker in my Angular Google Map in real-time, but unfortunately it is not working as expected. It only displays the initial static data and then fails to update. Despite conducting a thorough search on Google, I have be ...

Tips on sorting a nested array in a React TypeScript project

Hey there! I currently have a working filter in React that utilizes a List (I am using Mantine.dev as my CSS template): <List> {locations.filter(location => { const locServices: Service[] = []; location.services.forEach(service => { ...

Encountering a build error in ng serve right after running npm install

After deleting the node_modules directory and rebuilding it with npm install, I encountered an error in my angular2 app when using cmd ng serve. Error: 'common-tags' module not found at Function.Module._resolveFilename (module.js:337:15) ...

What is the process for defining custom properties for RequestHandler in Express.js middleware functions?

In my express application, I have implemented an error handling middleware that handles errors as follows: export const errorMiddleware = (app: Application): void => { // If the route is not correct app.use(((req, res, next): void => { const ...

Exploring TypeScript's Index Types: Introduction to Enforcing Constraints on T[K]

In typescript, we can utilize index types to perform operations on specific properties: interface Sample { title: string; creationDate: Date; } function manipulateProperty<T, K extends keyof T>(obj: T, propName: K): void { obj[propName] ...

Setting the default value for a dropdown in Angular 2 using Kendo UI

I'm currently facing an issue with creating a dropdownlist using Kendo UI. The problem arises when I try to set a default selected value upon loading the screen. Referring to their documentation, my code is structured like this: HTML: <kendo-drop ...

Typescript enables bidirectional control of Swiper

I attempted to use the two-way control slider example from Swiper documentation, but I encountered TypeScript errors that prevented it from working correctly. Is there a way to make it compatible with TypeScript? The specific errors I received were: TS23 ...

Stop allowing the entry of zero after a minus sign

One of the features on our platform allows users to input a number that will be automatically converted to have a negative sign. However, we want to ensure that users are unable to manually add a negative sign themselves. We need to find a solution to pre ...

Stop committing changes in Git when there are any TypeScript errors found

While working on my project in TypeScript using Visual Code, I encountered a situation where I was able to commit and push my changes to the server through Git (Azure) even though there was an error in my code causing a build failure. It made me wonder i ...

I am encountering an issue where Typescript paths specified in the tsConfig.app.json file are not resolving properly

I have defined path settings in my tsconfig.app.json file like this: "paths": { "@app/core": ["./src/app/core"] } Every time I run a test that includes import statements with relative paths, it throws the following error: ...

Is it feasible to update just one key within an exported type using setState in TypeScript?

Recently, I decided to dive into Typescript within my React App and encountered an error that has left me stumped. I'm wondering if it's possible to access a specific key in an exported type and modify its value? Here is how I've exported ...

typescript: the modules with relational paths could not be located

As part of a migration process, I am currently converting code from JavaScript to TypeScript. In one of my files 'abc.ts', I need to import the 'xyz.css' file, which is located in the same directory. However, when I try to import it usi ...

Combining multiple forms in Angular 8页面

In my Angular 8 project, I am working on creating a registration/login screen with some animation effects when switching between the two forms. Each form has its own validation rules using form groups. However, I have encountered an issue where the registr ...