What is the best way to display an error message for a dynamic form array in Angular?

I created a dynamic form array where clicking the add contact button inserts a dynamic form field. I successfully implemented validation for the form fields (using validator.required, validator.pattern, etc.).

However, when attempting to display an error message in the HTML view:

<md-error *ngIf="myForm.controls.myContactArray.controls['name'].hasError('required')">
      Email is <strong>required</strong>
    </md-error>

The following error message occurred:

core.es5.js:1020 ERROR TypeError: Cannot read property 'hasError' of undefined
    at Object.eval [as updateDirectives] (RegisterComponent.ngfactory.js:453)
    at Object.updateDirectives (core.es5.js:12770)
    ...

HTML

<div class="container-fluid">
  <md-card>

    <button (click)="addColumn()" md-raised-button>Add Contacts</button>
    <hr>

      <form  [formGroup] = "myForm" (ngSubmit) = "save(myForm.value)" class="contact-form">

        <div formArrayName="myContactArray">
          <div *ngFor="let myGroup of myForm.controls.myContactArray.controls; let rowIndex = index" >
            ...

          <button md-raised-button type="submit" *ngIf="myForm.controls.myContactArray.controls.length > 0"  [disabled] = "!myForm.valid">Submit</button>

      </form>

    </md-card>
  </div>

TypeScript

import {Component,OnInit} from '@angular/core';
import {FormControl,FormBuilder,FormGroup,FormArray,Validators} from '@angular/forms';

const EMAIL_REGEX = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
...

@Component({
    moduleId: module.id,
    selector: 'app-register',
    templateUrl: './register.component.html',
    styleUrls: ['./register.component.css']
})

export class RegisterComponent implements OnInit {
    
    ...

}

Answer №1

After reviewing your feedback, it appears that you are looking to display only one error message at a time.

However, in order to achieve this, you must specify the form group to which you want to apply the validation errors. For instance:

myForm.controls.myContactArray.controls['name'].hasError('required')

This code snippet is attempting to access a form control named name within the form array, rather than a specific form control inside a form group.

To address this correctly, you should use the myGroup identifier for each form group within the form array. Then, if there is a nested form group within that group, like myGroupName[rowIndex], you can handle validation errors as follows:

<md-error *ngIf="!myGroup.controls[myGroupName[rowIndex]].hasError('minlength', 'name')"> 
    Name is required
</md-error>

Answer №2

Consider incorporating

*ngIf="myForm.hasError('required', 'name')"

A peculiar error came up for me not long ago, so if you encounter an argument issue, consider using this alternative

*ngIf="myForm.hasError('required', ['name'])"

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

Using React components within an Angular 6 application: A comprehensive guide

Looking for advice on how to reuse React components in an Angular 6 application. Can anyone recommend the best approach for accomplishing this? ...

Learn how to define an array of member names in TypeScript for a specific type

Is there a way to generate an array containing the names of members of a specific type in an expression? For example: export type FileInfo = { id: number title ?: string ext?: string|null } const fileinfo_fields = ["id","ext&qu ...

The function item$.take cannot be found, resulting in a TypeError: "item$.take is not a function"

I am currently facing an issue with the take(1) function not working as expected with my Angular Firebase object. I have tried using valuechanges and snapshotchanges as alternatives, but they do not solve the problem for me due to other issues I encounter. ...

How can RxJS be used to handle only the first value returned when calling multiple URLs?

I am faced with the challenge of having multiple URLs containing crucial information. My goal is to find a specific ID within these URLs, but I do not know which URL holds the necessary details. The approach I'm taking involves calling each URL and us ...

Tips on saving a moved option item from one table to another in HTML:

Having an issue with dragging tables between different lists in Angular. The tables are generated by separate ngFor loops and I am using cdkDrag for the drag and drop functionality. The problem arises when I set an option in a dropdown and then drag the ta ...

Error encountered in Ionic Angular: Camera-Injection-Error provider is missing in Module.ts

Having some trouble while trying to develop an app with ionic-angular using the Ionic/ngx camera. I keep encountering this error even after adding the camera provider in the module.ts section. View the error here Below is my module.ts file content: impo ...

Attempting to incorporate NestJS modules into an NX monorepo is a task that Angular is currently

Recently, I encountered a frustrating issue while working with a monorepo that contains both Angular and NestJS. In an attempt to access DTOs, I made the mistake of including NestJS files on the client side. This caused Angular compilation errors due to de ...

Issues occur during installation of Angular on Mac Catalina, encountering errors while trying to run the installation command for Angular: `% sudo npm

My npm version is 6.14.6 and node version is v12.18.3. I have attempted the following: Added sudo in the beginning, but still not working. Tried to install har-validator using command: sudo npm install har-validator Attempted: npm install --force expo-cli ...

Assign the value of a state by accessing it through a string path key within a complexly

I'm currently attempting to modify a deeply nested value in an object by using a string path of the key to access the object. Here is my setup: const [payload, setPayload] = useState({ name: "test", download: true, downloadConfi ...

Validating React Typescript Props: Ensuring that two specific props do not exist simultaneously

Currently, I'm developing a reusable component in React-Typescript and I am looking to validate my props OnClick and component as follows: Both onClick and component prop are optional. These props will only be passed to the component if they need to ...

Setting up Linter and Prettier to enforce rules in HTML

My team and I in our Angular project have established certain rules regarding template formatting and Sass stylesheets. We utilize linter and prettier within our project. I am now curious if there is a way to configure these tools to automatically enforce ...

Exploring the World of ESLint, Prettier, Typescript, and VScode Configuration

There is a common belief that Prettier is the preferred tool for formatting, while ESlint is recommended for highlighting linting errors, even though ESlint also has formatting capabilities. However, it should be noted that Prettier lacks certain advanced ...

Having difficulty installing TypeScript on my machine

https://i.stack.imgur.com/l6COf.pngHaving trouble installing TypeScript with the following error: npm WARN registry Using outdated package data from https://registry.npmjs.org/ due to an error during revalidation. npm ERR! code E500 npm ERR! 500 Interna ...

Jest.useFakeTimers() causing clearTimeout test to malfunction

I've been exploring the transition to the newer version of jest.useFakeTimers(), which is not set as default in the latest 27.x release. Encountering some issues during my tests, Jest keeps flagging that functions like clearTimeout and setInterval a ...

automatic slideshow plugin for Ionic 4

I've been working on implementing an auto slide feature for Ionic 4, but I'm having trouble getting it to work. Here's the code snippet: page.ts ========= @ViewChild(IonSlides) slider: IonSlides; options: { autoplay: true } HTML ...

Unpacking the information in React

My goal is to destructure coinsData so I can access the id globally and iterate through the data elsewhere. However, I am facing an issue with TypeScript on exporting CoinProvider: Type '({ children }: { children?: ReactNode; }) => void' is no ...

Learn the process of seamlessly uploading various document formats, videos, and previewing documents with Angular software

I am having trouble viewing uploaded files in the carousel. While I can see video and image files, other document formats are not displaying. Can someone please recommend a solution to enable viewing all types of documents as well? mydata = [] onSelect ...

Setting up the production environment

I'm attempting to set up my app in the production environment by executing ng serve --configuration=production However, I'm encountering the error message "An unhandled exception occurred: Project 'production' does not support the &a ...

Tips for storing the device token received from Firebase Cloud Messaging in an Ionic2 application

Using the FCM plugin for ionic2, I was able to successfully implement push notifications. For reference, you can check out the plugin here. I followed the steps outlined in this Github repository, and everything is working smoothly so far. Now, my next go ...

Utilize modules within the AppModule to promote modularization and maintain separation of concerns in Angular 2

When using templates like those from the ASP.NET Core JavaScript services, typically a single module named AppModule is included. However, in my application, which is divided into two logical areas (AreaA and AreaB), I thought it would be better to use two ...