What is the correct method for incorporating validators into an already existing set within a Custom Form Control?

I'm questioning the validity of my solution. My application utilizes Reactive Form, and for my CustomFormControl (which implements ControlValueAccessor), I've included a validator

myControl: ["", Validators.required]
. This validator is only required on certain pages, so it's added by the formBuilder.

However, there is also a need for validators that are always applied to that control. To achieve this, I had to introduce the token NG_VALIDATORS, which allows me to utilize the validate() method that gets triggered every time the control needs validation:

@Component({
    selector: "my-control",
    templateUrl: "./my-control.component.html",
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: MyControlComponent,
            multi: true
        },
        {
            provide: NG_VALIDATORS,
            useExisting: MyControlComponent,
            multi: true
        }
    ]
})
export class MyControlComponent implements OnInit, ControlValueAccessor {

    ...

    validate(value: AbstractControl): void {
        value.setValidators(Validators.compose([value.validator, Validators.min(0), Validators.max(200)]));
    }
}

It's worth mentioning that I used value.validator in order to merge the existing validators added in the form builder with the new min and max validators. The functionality works as expected, but I'm unsure if this is the correct approach, since I couldn't find a similar case when searching online.

Answer №1

After some research, I discovered a more efficient approach by including validators directly in the providers array.

providers: [
    {provide: NG_VALIDATORS, useValue: Validators.minLength(3), multi: true},
    {provide: NG_VALIDATORS, useValue: Validators.maxLength(10), multi: true},
]

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

Is it possible for a ngrx signal feature store to retrieve the state of the store that it is consuming?

I am interested in creating a feature store that can receive input or reference a state from the store which interacts with or consumes the store, such as the parent of the ngrx signal feature store. For instance, imagine I have a store named "withCounter ...

Expecting null in Angular2/Jasmine tests can lead to browser crashes

I'm currently experiencing issues with testing a particular component. Here is the test that I am running: describe('SmpEventsNewCompactEventComponent', () => { const specService: SmpSpecService = new SmpSpecService(); describe(&ap ...

To enable iteration of iterators when trying to spread, utilize the TypeScript compiler option '--downlevelIteration'

I have a function that accepts an argument of either an object or an array. const handleScenarioChange = (scenario: Scenario | Scenario[]) => { if (isArray(scenario)) { const scenarios = [...state.selectedScenarios, ...scenario]; const unique ...

I am currently working on an Angular 8 project and experiencing difficulties with displaying a specific value from a JSON object in my template using an ngFor loop

Apologies if I am not familiar with all the terms, as I am mostly self-taught. I started with Udemy and then turned to Stack Overflow to tackle the more challenging aspects. This platform has been incredibly valuable and I am truly grateful for it. Now, l ...

Automatically focus on the button

Encountering an issue where setting focus on a button upon the input key enter event is not working. While setting focus on inputs functions properly, using the same code on a button does not work at all. Sample HTML Component: <form [formGroup]=&apos ...

Angular Protectors: Stop unauthorized access to a URL while allowing authorized refresh

I've developed a Protection feature that blocks users from directly accessing a specific URL, and it's functioning correctly. However, the issue arises when I try to refresh the page as the Protection feature ends up redirecting me. Below is th ...

Managing simultaneous asynchronous updates to the local state

There is a scenario where a series of asynchronous calls are made that read from a local state S, perform certain computations based on its current value, and return an updated value of the local state S'. All these operations occur at runtime, with ...

Error with importing the angular-4-data-table package causing issues

After adding the angular-4-data-table package and importing DataTableModule in the app.module.ts imports section, I encountered an issue. The import statement: import {DataTableModule} from 'angular-4-data-table'; Upon running the ng serve comm ...

Watching the Event Emitters emitted in Child Components?

How should we approach utilizing or observing parent @Output() event emitters in child components? For instance, in this demo, the child component utilizes the @Output onGreetingChange as shown below: <app-greeting [greeting]="onGreetingChange | a ...

What is the best way to set the minDate and maxDate of the NgbDatePicker in the main component so that the settings can be applied

Within my Angular 4 project, I have integrated Ng-bootstrap (v1.1.0) which includes multiple date pickers across different modules. I am looking to enforce a global maxDate configuration for all these instances. Below is an overview of my folder structure: ...

A tutorial on ensuring Angular loads data prior to attempting to load a module

Just starting my Angular journey... Here's some code snippet: ngOnInit(): void { this.getProduct(); } getProduct(): void { const id = +this.route.snapshot.paramMap.get('id'); this.product = this.products.getProduct(id); ...

Passing data between two Angular directives using EventEmitter

Looking to share a variable between two directives in Angular 7 Check out the updated code here: https://stackblitz.com/edit/angular-ct49bn The issue arises when selecting a customer from the list, as the emitter fails to communicate with the other direc ...

Adjust the width of a div in Angular 6 based on a specified condition

I need to adjust the width of a div based on certain conditions. <div [ngStyle]="'width': selectedTab =='Home' ? '50%' : '100%'"> </div> The currently selected tab is stored in "selectedTab". There ...

Discovering a DOM Element Post Mouse Click Event Using HostListener in Angular 8

Is there a way to locate the current DOM element on a page after clicking the mouse? I am currently attempting to utilize HostListener in Angular 8. @HostListener('click') onClick(){ window.alert('Current DOM element is'); } ...

State array is being updated

In my main container, I am setting a context for its children : import React, {useRef, useEffect, useState, ReactNode, createContext, useContext} from 'react'; import Provider from "./Provider"; import Consumer from "./Consumer&quo ...

Tips for utilizing array.items in joiful validation?

Can someone provide an example code or a link on how to correctly use the joyful validation for array items? I attempted the array.items validation code using joyful, but I am not sure how to specify the items. Thanks in advance! ...

Issue with Angular2/4 Module: Unable to locate 'three' in the application directory

As a newcomer to Angular and TypeScript, I am encountering difficulties when trying to import the @types/three npm package. I have created a new Angular project and attempted to use the three package, but I keep receiving the following error: Module not f ...

Deploying Firebase functions results in an error

Just recently started exploring Firebase functions. Managed to install it on my computer, but running into an error when trying to execute: === Deploying to 'app'... i deploying firestore, functions Running command: npm --prefix "$RESOURCE_ ...

Error: The function webpackMerge.strategy does not exist

I've been in the process of updating an older Angular project to the latest version of Angular. However, I'm encountering a problem when trying to build, and I'm unsure why this is happening. Below is the error message that I've receiv ...

Struggling with sluggish performance on a certain project within VS Code

My experience with VS code has been excellent over the years, but I recently encountered a problem in one of my projects that caused a significant slowdown in performance. Strangely, other projects are working fine without any issues on VS code. I suspect ...