How can you store form field validation rules (for example, firstname.dirty) in an array within TypeScript in Angular?

How do I save form field validation rules in an array? What should replace /'''''HERE'''''/ with?

formfields:  Array<Object> = [
    {label: "Employer:", control: "employer", validations: "{requirederror: "employer.errors?.required && employer.dirty", notvaliderror: "employer.errors?.maxlength && employer.dirty"}"},
    {label: "Phone:",    control: "phone",    validations: "{requirederror: "phone.errors?.required && phone.dirty", notvaliderror: "phone.errors?.pattern && phone.dirty"},
    {label: "Email:",    control: "email",    validations: "{requirederror: "email.errors?.required && email.dirty", notvaliderror: "email.errors?.email && email.dirty"}"}
];

<div *ngFor="let formfield of formfields; let i = index">
     <div class="labelandinput">
          <label class="label">{{formfield.label}}</label>
          <input class="input" formControlName="{{formfield.control}}">
          <div class="formfielderror" *ngIf=" /'''''HERE'''''/ ">...</div>
          <div class="formfielderror" *ngIf=" /'''''HERE'''''/ ">...</div>
     </div>
</div>

Is it simply achieved like this?

  <div class="formfielderror" *ngIf="{{formfield.validations.requirederror}}"> SOME REQUIRED ERROR </div>
  <div class="formfielderror" *ngIf="{{formfield.validations.notvaliderror}}"> SOME NOT VALID ERROR </div>

Answer №1

Consider revising how you label your data. Traditionally, an array represents a collection of similar elements, with each element potentially being a JavaScript object that describes a specific item.

Let's say you're working with reactive forms. In this case, your array might resemble something like this:

myItems = [
 formBuilder.group({
   firstName: ['',[Validators.required(), Validators.pattern(/[0-9]+/)]],
   hobby: [''] // no validators here
 })
]

You can then display it using the following markup:

<div *ngFor="let item of myItems" [formGroup]="item">
  <input type="text" formControlName="firstName">
 <div *ngIf="item.firstName.errors?.required">First name is required. Please fill it in.</div>
 <div *ngIf="item.firstName.errors?.pattern">First name should follow the pattern [0-9]+.</div>
  
  <input type="text" formControlName="hobby">
</div>

I hope this example gives you a good starting point.

If you only need one form for each item, then an array may not be necessary. Simply use form = formBuilder.group({...}), and you won't need to iterate with *ngFor in the template.

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

Mastering Angular Apollo Error Resolution Methods

Hey everyone, I'm facing a problem with apollo-angular and apollo-link-error that I just can't seem to figure out. I've experimented with different approaches but have had no luck catching errors on the client-side of my angular web app. Bel ...

Encountered an issue during the Jest test where the error message states 'Cannot call Class constructor Stack without using the keyword 'new''

I have encountered an issue with my Jest test for an AWS CDK configuration import { expect as expectCDK, matchTemplate, MatchStyle } from '@aws-cdk/assert'; import * as cdk from '@aws-cdk/core'; import { KmsMultiregionPrincipalKey } fro ...

How can I convert an ArrayList to a String in Java?

Is there a way to print the reverse of a given number without using a for loop? I am struggling with printing an ArrayList in a specific format. How can I print the ArrayList [3, 5, 4, 1] as 3541 - without any brackets, commas, or spaces? If this is not f ...

Can you explain why it prints to the console twice every time I try to add an item?

This is a note-taking application created using Angular and Firebase. The primary functionalities include adding items and displaying them. I noticed a strange behavior where my ngOnInit() method is being called twice every time I add an item. As shown in ...

Strategies for Maintaining User Logins

As I test an Ionic2 application on my Android phone, I am faced with the challenge of maintaining user login within the app. The issue is that each time I close the app, I am prompted to log in again. Is there a way for users to stay logged in until they ...

Display two elements from the array on each line, with the elements separated by a comma

Can anyone assist me with this issue? I have an array containing 6 items, and I would like to display 2 items per line separated by commas. Here is the code I am currently using: $rates[] = array("2020-01-01"=>3000); $rates[] = array("2020-01-02"=>30 ...

Angular2 module encounters failure when trying to inject InjectionToken using @Inject()

I've recently encountered an issue with InjectionToken that is declared within a module. import {InjectionToken, NgModule} from '@angular/core'; import {SampleComponent} from './sample.component'; export let SOME_TOKEN = new Inje ...

Retrieve the object property based on an array of indices

I am looking to create a function that can retrieve a specific property of an object based on an array of property names const getObjectProperty = (arr: string[], object: any) { // This function should return the desired object property } Expected Outco ...

Searching for values in nested arrays using lodash.find

Presented below is an array where I aim to employ lodash for item search: [ { "itemA": "apple", "itemB": [ { "itemC": "1", "itemD": "red apple" }, { "itemC": "2", "itemD": "green apple" }, ...

Bring in services from a neighboring module within Angular 2

In my Angular 2 project, the module structure is as follows: app |-module1 |-module2 |-component2-1 |-component2-2 |-factories The factories module contains various providers defined in this manner: @NgModule({ provi ...

What steps can I take to ensure that the elements are in the same row instead of being displayed in three separate rows?

(I'm a beginner in web development and need some help) Is there a way to align elements into the same row instead of stacking them up in separate rows? I'm working on creating a header bar similar to the one on the Naive UI Documentation Website. ...

Is there a way to use Css Autoprefixer on multiple files at once with a single function

My project built with Angular2 contains over 100 CSS files that do not have any prefixes for browsers like Mozilla or Chrome. I am looking for a tool, gulp task, or anything else that can automatically add prefixes to all of my CSS files. I attempted to u ...

The use of Next.js v12 middleware is incompatible with both node-fetch and axios

I am facing an issue while developing a middleware that fetches user data from an external endpoint using Axios. Surprisingly, Axios is not functioning properly within the middleware. Below is the error message I encountered when using node-fetch: Module b ...

Importing a JSON or JSONC file into a vite/typescript project can be easily done

I am looking for a way to seamlessly share my routes between my actix-web backend and Vue with Vue-Router frontend without needing separate route files. I want to define the routes on the frontend without having to make any changes on the server side. If t ...

What is the process for navigating from one page to another in Ionic 2?

I am currently attempting to navigate between pages using ionic 2. I have been studying from the resources provided at https://ionicframework.com/docs/v2/api/navigation/NavController/ export class ApiDemoPage { constructor(public navCtrl: NavControlle ...

Issue with page break functionality during print preview

div.pagebreak { page-break-after: always; page-break-inside: avoid; } HTML <!-- Page separator --> <div class="pagebreak" style="float: none;"><hr class="hidden-print" /></div> <app-mud-chec ...

What is the best way to invoke a function from a Service to a Component in Angular?

Currently, I am in the process of learning Angular and recently created an alarm clock feature. In this functionality, users have the option to select alarms they wish to cancel by using checkboxes that are then stored in local storage through the use of & ...

Encountering Kubernetes Ingress Error: 502 Bad Gateway - Connection Refused

I am facing an issue while trying to access my Angular front-end deployed on an AKS cluster at Path / with the service named lawyerlyui-service. The cluster is using nginx deployed via HELM with the official chart () I have other backend .net core services ...

Utilize existing *.resx translation files within a hybrid application combining AngularJS and Angular 5

Greetings! I currently have an AngularJS application that utilizes $translateProvider for internalization and WebResources.resx files: angular.module('app') .config(['$translateProvider', 'sysSettings', 'ngDialogProv ...

Different varieties of TypeScript's keyof when working with objects

I am grappling with the concept of TypeScript's types when incorporating the keyof type operator on objects. Check out this example: type TypeA = { [k: number]: boolean }; type AKey = keyof TypeA; // ^? type AKey = number type TypeB = { [k: string] ...