Creating dynamic validation attributes for input fields in Angular Reactive Forms through interpolation

It appears that a similar issue was discussed in this Stack Overflow thread, however, I am specifically seeking a solution using Angular instead of AngularJS.

Within my Reactive Forms, I have implemented validators as shown:

public contactForm: FormGroup = this.formBuilder.group({
  ...
  formControlDescription: [
    '',
    Validators.compose([
      Validators.maxLength(5000),
      Validators.minLength(30),
      Validators.required,
    ]),
  ],
  ...
});

In the html file, I currently have the number 5000 hardcoded like this:

<mat-hint align="end">{{ contactForm.get('formControlDescription')!.value.length }} / 5000</mat-hint>

Question: Is there a way to dynamically access and display the Validators.maxLength(5000) for formControlDescription from contactForm in the html?

Answer №1

If you want to retrieve the error object from min/max validators, you can do so like this:

<mat-hint align="end">{{ contactForm.get('formControlDescription')?.errors.maxlength?.actualLength }} / {{ contactForm.get('formControlDescription')?.errors.maxlength?.requiredLength }} </mat-hint>

Here is a cleaner version of the code:

<mat-hint align="end">    
  {{ contactForm.errors?.formControlDescription?.maxlength?.actualLength}} / 
  {{ contactForm.errors?.formControlDescription?.maxlength?.requiredLength}}
</mat-hint>

For more information, refer to the maxLength Validator documentation

Update

The values of angular validators will only be accessible when the validator detects an invalid input.

For example, with minLength(10), it will flag as invalid until there are 10 or more characters. Similarly, for maxLength(20), the values will only appear in the errors object when the user exceeds 20 characters.

This can be problematic if you need to consistently display actualLength and requiredLength to the user. Therefore, it's recommended to use a separate variable to handle this. Example:

const validatorOptions = {
  maxLength: 5000,
  minLength: 5
}

Then, in your template, use it like this:

<mat-hint align="end">{{ contactForm.controls.formControlDescription?.value.length }} / {{validatorOptions.maxLength}}</mat-hint>

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

Ways to address observables in Angular in a manner similar to deferred objects

Transitioning from AngularJS to Angular has posed a challenge for me, especially when it comes to moving from promises to observables. Below is an example of my code in AngularJS: var deferred = $q.defer(), frame = document.createElement('newFrame ...

When making a GET request using Angular HttpClient, an error message stating "No overload matches this call" may

One issue I am facing is with a GET method in my backend. When sending a request body as input, I receive a list of results in return. However, the problem arises in my frontend: search(cat: Cat): Observable<Cat[]> { return this.httpClient.ge ...

Performing addition in Angular 2 with the help of TypeScript

Here is a code snippet of a component I have written: export class AppComponent { public num1: number = 2; public num2: number = 3; public sum: number = 0; public add() { this.sum = this.num1 + this.num2; } } However, when I r ...

A step-by-step guide on making a web API request to propublica.org using an Angular service

Currently, I am attempting to extract data from propublica.org's congress api using an Angular 8 service. Despite being new to making Http calls to an external web api, I am facing challenges in comprehending the documentation available at this link: ...

Exploring the implementation of the jquery .counterUp function within Angular 5

I am working on implementing a counter up view for my company's website using the jQuery counterUp function. Despite adding script tags for it, Angular is not recognizing the function. if(st >= hT ){ $('.counter').counterUp({ dela ...

Encountering an issue in an Angular project where it remains stuck at the preloader stage

Whenever I attempt to redirect to the home page, the URL path changes but the preloader continues to load without rendering the home page until I hard reload the page. Even when I remove the preloader, the page still does not render until I hard reload it. ...

Unwrapping nested objects in a JSON array with JavaScript: A step-by-step guide

After trying some code to flatten a JSON, I found that it flattened the entire object. However, my specific requirement is to only flatten the position property. Here is the JSON array I am working with: [{ amount:"1 teine med 110 mtr iletau" comment:"" ...

What is the best way to identify the main dark color in Angular Material, and what other color variables are available for use with Angular Material?

Hey there, I'm trying to figure out how to utilize the primary dark color from angular material. I attempted using color="p-dark" but it doesn't seem to be working. Any ideas on how to access the dark color defined by the material color tool? I w ...

Creating a dynamic form in Angular using reactive forms and form builder that pulls real-time data from the server

I have been struggling for the past two days to organize the data in the correct order but so far, I haven't been successful. Essentially, I retrieve some data from the server and present it to the client along with additional fields that the client n ...

What is the best way to ensure that md-select takes up 100% of the

I am currently utilizing the latest version of Angular. The following code snippet pertains to material design: <md-grid-tile> <md-select placeholder="Favorite food" [(ngModel)]="selectedValue" name="food"> </md-select> </md-grid-ti ...

Failure to execute custom scripts in package.json

NPM 8.1.2 Node.js 16.13.1 (downloaded and installed the LTS versions from https://nodejs.org/en/) I am trying to utilize custom scripts to launch my Angular application. { "name": "TestApp", "version": "0.0.0", ...

The 'innerText' property is not present in the 'Element' type. (2339)

Recently, I've been working with javaScript and I encountered some issues while writing a function. Strangely, I kept receiving error messages that I couldn't quite understand. Initially, there was a problem where every time I tried to create a j ...

Retrieval Error: the request was unsuccessful

I'm encountering an issue while following a tutorial to create a Twitter clone using Next.js, Tailwind CSS, and TypeScript. https://www.youtube.com/watch?v=rCselwxbUgA&t=1357s&ab_channel=SonnySangha 1:42:05 / 3:17:52 Although I followed the ...

Customizing a generic method in typescript

I am currently working on developing a base class called AbstractQuery, which will serve as a parent class to other classes that inherit from it. The goal is to override certain methods within the child classes. class AbstractQuery { public before< ...

Angular can tailor its view templates to suit either mobile or desktop platforms

I'm currently developing an application that requires displaying different views depending on whether the site is accessed from a desktop or mobile device. While I already have a responsive design in place, I want to incorporate ionic components for a ...

AG-Grid hierarchical data structure

Transitioning from kendo tree list to ag grid tree data grid, I am facing a challenge. My table data is currently formatted as shown below, but ag grid requires data in the form of a string array of nodes in a tree. How can I adapt or customize my existing ...

The error message "better-sqlite3 TypeError: o.default is not a constructor" indicates that

As part of my vscode extension development in typescript, webpack, and better-sqlite3, I am attempting to create a database within the C:\Users\userName\AppData\Roaming\Code\User\globalStorage\ folder. However, when ...

Press the second form submit button after the completion of another Observable

Below is the unique process we aim to accomplish using solely RXJS Observables: Press Login button (form with username & password). We bind Observable.fromEvent with our form. Upon submitting the form, call loginUser() to send an http request to serv ...

The instance is referring to a property or method that is not defined, but being used during rendering. Verify that the property is reactive and included in the data option

I'm a newcomer to vue JS and facing a challenge with creating vue class components. My setup includes: @rails/webpacker: "^5.1.1" typescript: "^4.0.2" vue: "^2.6.11" vue-class-component: "^7.2.5" Below is the ...

Navigate back two levels (../../) using Angular2's relative navigation

One issue I am currently experiencing with my application is related to the functionality of a back button that navigates back through multiple levels. When navigating back one level, the code snippet below works perfectly, resulting in a route URL of http ...