Utilizing Angular 11 for interactive form input validation

I have been working with Angular 11 to create dynamic form inputs and I am facing a challenge with validating the form fields that are added dynamically when clicking the "add" button. I have tried multiple solutions but haven't found the right one yet. Below is a snippet of my code:

Component.ts file

this.pollAdd = this.fb.group({
      question: ['',Validators.required],
      queChoices:this.fb.array([this.createChoice()]),
    });

addChoice(){
    this.queChoices=this.pollAdd.get('queChoices') as FormArray;
    this.queChoices.push(this.createChoice());
  }

  createChoice():FormGroup{
    return this.fb.group({
      choice:['',Validators.required],
    })
  }

get f() { return this.pollAdd.controls; }

In Component.html file

<div formArrayName="queChoices" *ngFor="let choices of pollAdd.get('queChoices')['controls'];let i=index;">
        <mat-form-field class="ch__custom_input w-100 mt-3" [formGroupName]="i">
          <mat-label>Choice {{i+1}}</mat-label>
          <input matInput formControlName="choice" autofocus/>
        </mat-form-field>
      </div>

Could someone please guide me on how to validate each choice field in this scenario?

Answer №1

Retrieve the name and verify for any potential errors, similar to a standard form.

<div *ngIf="choice.errors?.required">Choice must be selected</div>

Answer №2

<div *ngIf="options.controls['option'].errors && options.controls['option'].touched">
            <mat-error *ngIf="options.controls['option'].errors?.required">Option {{i+1}} is required!</mat-error>
          </div>

Seems to be functioning perfectly for me...

Answer №3

When using mat-error, a unique error eliminates the need for *ngIf, making it simpler

<mat-error>required</mat-error>

A function can also be utilized like this:

getErrorMessage(inputRef:MatFormField) {
  const control=inputRef._control?inputRef._control.ngControl:null;
  if (!control || !control.errors)
    return null;
  if (control.hasError('required')) {
    return 'You must enter a value';
  }

  return control.hasError('email') ? 'Not a valid email' : '';
}

The mat-field is then passed to the getErrorMessage function using a template reference variable

<mat-form-field #inputRef appearance="fill">
  <mat-label>Enter your email</mat-label>
  <input  matInput placeholder="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4636273206233e272b362a236825292b">[email protected]</a>" [formControl]="email" required>
  <mat-error>{{getErrorMessage(inputRef)}}</mat-error>
</mat-form-field>

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 there a method to trigger the opening of a calendar downwards within a modal?

I am having an issue with a p-dialog that contains a p-calendar. The problem is that when I try to open the calendar, it pops up upwards instead of downwards. <p-dialog responsive="true" modal="true" (onHide)="closeDialog()" #genericDialog [(visi ...

Establish a connection between an Angular client and a Spring backend using JWT for authentication

I successfully integrated JWT into my Spring backend by following the steps outlined in this informative guide: https://auth0.com/blog/securing-spring-boot-with-jwts/ Interestingly, when I perform a PUT request using Postman, everything seems to be workin ...

Is it possible to integrate React-three-fiber into an Angular application?

After creating an Angular application that heavily relies on three.js, I discovered React-three-fiber and fell in love with it. Rather than rebuilding the entire app in React, I am curious if there is a way to embed React and react-three-fiber within my ...

The addition of types/cors in Express Typescript causes my POSTMAN request to hang indefinitely

I am experiencing an issue with my React web app and Express TypeScript backend. Previously, my POST request was functioning well, but now it seems to hang indefinitely on Postman without returning any errors. issueController.ts import { RequestHandler } ...

Guide on creating dynamic components within an ngFor loop using component outlet

I am currently working on code that generates a series of components based on component type within an ngfor loop <div class="outlet"> <app-customer-personal-details [selectedCustomer]="selectedCustomer"></a ...

Tips for simulating behavior in express using Typescript and the Mocha library

Help with mocking 'Request' in Mocha using express with Typescript needed! Here is the current approach: describe("Authorization middleware", () => { it("Fails when no authorization header", () => { const req = { ...

Issue with offline functionality in Angular 8 PWA assetGroups

I developed a Progressive Web App using Angular 8.1.0, and I encountered an issue when testing it offline on my mobile device. The images and fonts in the asset groups are not loading properly. For instance, here is an error related to the logo image from ...

Reimagine server-side storage options as an alternative to remixing JavaScript local storage

My remix application is designed to serve as a frontend. I retrieve data from the backend and sometimes need to load specific data only once and reuse it across multiple pages. In our previous frontend setup, we utilized localstorage; however, with the cur ...

Error: Angular 6 and karma have encountered a problem - "Unable to load "@angular-devkit/build-angular", as it is not recognized."

Upon upgrading to the latest version of Angular, my karma tests ceased functioning and started crashing with this error log: 14 04 2018 14:17:00.453:ERROR [preprocess]: Can not load "@angular-devkit/build-angular", it is not registered! Perhaps you ar ...

Incorporate all photographs from a designated directory in the gallery into an Angular 6 PWA Application

Currently, I am developing a Progressive Web Application that requires me to showcase all images stored under a specific directory (for instance, all pictures saved in the "Downloads" folder on a mobile device) within a personalized grid view. I would lik ...

Trouble with getting 'files.exclude' to work in Visual Studio Code

Recently, I made changes to my files.exclude user settings in Visual Studio Code to hide .js and .map files, which were working fine yesterday. However, today, without restarting or closing the application, it suddenly stopped working. Here is the complet ...

What is the best way to trigger a parent component to reload from within its child component?

I developed this application using Angular 17 (standalone) and Ionic 7. In the structure, Tab1Page acts as the parent component with "cards", while ItemCardComponent functions as its child showcasing a Swiper carousel of ion-cards that retrieve values from ...

The process of extracting values from an HTML tag using Angular interpolation

I am working on an Angular application that has the following code structure: <p>{{item.content}}</p> The content displayed includes text mixed with an <a> tag containing various attributes like this: <p>You can find the content ...

The Material UI Grid is not compatible with the Chrome DevTools Device Toolbar and may not function properly

Using MUI v5 with React and Typescript has been an interesting experience for me. When I utilize the Grid system, I set options like xs sm md lg to define item width. Interestingly, setting just xs or sm works fine, but when I include md, other options su ...

Utilize Angular 2 Form Elements Again

I'm currently in the process of working on a project with Angular and I want to make sure that my form components can be used for creating and updating entities seamlessly. Let's say I have a User entity stored on a remote API, and I have a form ...

Testing TypeScript data types through unit tests

In one of my modules, I have the following export: export class Action1 implements Action {} export class Action2 implements Action {} export type ActionsUnion = | Action1 | Action2; I'm currently exploring the best approach to testing Actions ...

Issues with the File plugin in Ionic 2

Currently, I am working on integrating Quickblox into my Ionic2 application. I have successfully implemented all the required functionalities except for file uploading. In Quickblox, there is a specific function that needs to be used for uploading files, a ...

The step-by-step guide to fixing a Gigwage client eslint error using nestJS

Whenever I utilize the gigwage client for my services, I encounter the following eslint error: TS2742: The inferred type of 'findAll' cannot be named without a reference to '@gigwage/client/node_modules/axios'. This is likely not porta ...

Looping through the values of an Observable and subscribing to a new Observable

In this scenario, we have an Array nested within an Observable. For each value in the array, we need to make an API call, which returns another Observable. Let's simplify it with an example. How can I ensure that the variable data actually contains th ...

Angular ESLint Error: Sorting issue with Decorated class members

While transitioning a TSLint Angular project to ESLint, I ran into an issue configuring @typescript-eslint/member-ordering. My goal is to maintain the decorated setters after other decorated fields: // place before decorated setter @Input() foo: boolean; @ ...