Form Validation in Angular Using Async Injection of Services

I am working on a custom async validator within a reactive form that requires validation of name uniqueness by making a call to a service.

Due to the purity of validators, I am struggling to find a proper way to inject a provider like HTTP to handle these validations.

The current implementation involves returning a function that includes the service, but it feels a bit like a workaround...

export function nameValidator(platformService: PlatformService): ValidatorFn {
    return (control: FormControl): { [key: string]: any } => {
        return userService.getUnique(control.value);
    };
}

So, my question is: Is there a more efficient way to approach this?

Answer №1

Validators have the capability to be injectable directive classes when utilized as directives within templates.

When specified directly in FormControl or FormBuilder, they are anticipated to be functions.

To utilize Dependency Injection (DI), they must be provided as useFactory or useClass and injected into a component:

@Injectable()
class NameValidator implements AsyncValidator {
  constructor(private userService: UserService) {}

  validate = (control: FormControl) => this.userService.getUnique(control.value);
}

...

new FormControl('', nameValidator.validate);

Note that the validate method is passed as a callback and should either be an arrow function or bound to the class instance using bind.

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

Looking to retrieve CloudWatch logs from multiple AWS accounts using Lambda and the AWS SDK

Seeking guidance on querying CloudWatch logs across accounts using lambda and AWS SDK Developing a lambda function in typescript Deploying lambda with CloudFormation, granting necessary roles for reading from two different AWS accounts Initial exe ...

Creating a personalized menu using Nextron (electron) - Step by step guide

I'm currently in the process of developing an app with Nextron (Electron with Nextjs and Typescript). Although I have the foundation of my Next app set up, I've been encountering issues when attempting to create a custom electron menu bar. Every ...

What is the best way to organize the data retrieved from the api into a map?

In my search page component, I display the search results based on the user's query input. Here is the code snippet: "use client"; import { useSearchParams } from "next/navigation"; import useFetch from "../hooks/useFetch&qu ...

The namespace does not have any exported object named 'LocationState'

I encountered the following issue while attempting to execute my TypeScript application: Namespace '"C:/DevTools/git/motor.ui/node_modules/history/index"' has no exported member 'LocationState'. Here is a snippet from my pack ...

Clearing Cache in NodeJS and Angular 6: A Comprehensive Guide

Currently, I have my Angular app hosted on NodeJS and am starting the application with npm start. This command bundles Angular and runs it along with the NodeJS server. However, it appears that after making changes to an Angular file (one of the .ts files ...

Angular 2+ with Customized Styles for Different Users

I'm facing a scenario where I need to apply different styles based on the clients/users accessing the site. Since all clients will be visiting the same site, I'll have to dynamically load styles based on the client that has logged in. What is t ...

Angular-Serviceworker: The start URL fails to return a 200 status code when offline

Recent Versions "@angular/common": "~9.0.0" "@angular/service-worker": "~9.0.0" Exploration Utilizing the service-worker was achieved by executing ng add @angular/pwa --project [app] which triggered Lighthouse to acknowledge the web-app as a PWA. Howev ...

An error occurred in Nest JS, specifically in the node_modules/jest-diff/build/diffLines.d.ts file at line 8, character 13. The error message is "error TS1005:

Whenever I start and run the NestJS app in watch mode by using the npm run start:dev command, I encounter the following error: ERROR in node_modules/jest-diff/build/diffLines.d.ts(8,13): error TS1005: '=' expected. node_modules/jest-diff/build/d ...

One way to display a table is by populating it with data from an API. If the table does

Within my Angular 6 application, there exists a table that displays data fetched from a web api. Additionally, I have incorporated some ngIf containers. One of these containers is programmed to exhibit a message in case the web api data turns out to be emp ...

Implementing a dependent <select> within an HTML table is a useful feature to enhance user experience and organization of

I have set up a table with editable columns where values can be selected from a drop-down menu. I achieved this by using HTML select. The options in the 'Category tier 2' column are based on the selection made in the 'Category tier 1' c ...

How to show ngFor value from Angular in a separate tag

I have a list of companies that I want to display in the following format: <div class="col-md-4"> <select ngModel="selectedCompany" style="width:400px;"> <option *ngFor="let x of mycompanylist&q ...

Changing the Value of an Input Element Dynamically in React: A Step-by-Step Guide

In a scenario where I have a component that takes an element, such as <input />, and I need to update its value programmatically after 15 seconds. Initially, I had the following approach in mind: const MyComponent = (myInput: JSX.Element) => { ...

Strategies for successfully passing mock dates as event values when unit testing in Angular

I have a function that requires date data from a datepicker event. I am using matdatepicker for selecting a date from the UI. I need help passing the date event value to my onDateSelected() function. Could someone assist me in passing the date event valu ...

Guide to dynamically resizing the Monaco editor component using react-monaco-editor

Currently, I am integrating the react-monaco-editor library into a react application for viewing documents. The code snippet below showcases how I have set specific dimensions for height and width: import MonacoEditor from 'react-monaco-editor'; ...

How can you retrieve data in Angular through an API call using the get method?

How can I make an API call to retrieve data from this URL, , using a GET method without passing any parameters in my Angular application? What is the code snippet required for this, and do I need to import any specific libraries or declare specific variabl ...

Error encountered following the upgrade of Angular and RxJS 5 to 6: Compilation failed

Since updating my libraries to the latest Angular 6 and RxJS 6, I've encountered an issue. I have a RouteService class that functions as a service. It utilizes the HttpClient to fetch data from a remote API. However, after the update, I'm facing ...

Having trouble with errors when trying to implement react-router-v6 with typescript

Having trouble with my code and receiving the following error: "Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element | DocumentFragment'. Type 'null' is not assignable to type 'Element | ...

Issue encountered while creating a Telegram Bot: Firebase Cloud Functions throwing an error message of "TypeError: Cannot read property 'slice' of undefined"

Greetings! I am currently in the process of developing a Telegram bot using Firebase cloud functions with Typescript. Despite my bot successfully executing its tasks, there seems to be an issue that is keeping my cloud functions persistently active, leadi ...

Error: Failed to execute close function in inappbrowser for Ionic application

Working on integrating the "in-app-browser" plugin with my Ionic project. Check out the code snippet below: const browser = this.iab.create(mylink, '_blank'); browser.on('loadstop').subscribe( data => { if ...

Generate Angular 9 HTML-formatted output with a return function statement

I am currently working on displaying a table using ngFor. I have encountered an issue with one particular column where a string needs to be displayed as two separate lines. I attempted to split the string into two array values using a function, but when re ...