Review all control documents

I initialize a formGroup like so

this.availableSigners = new FormGroup({
        nameSigner: new FormControl(),
        mailSigner: new FormControl()
});

and in my HTML component I have the following structure

<div *ngFor="let signer of signers;  let i = index">
                    <div class="form-row">
<div class="card-body col-md-4" style="padding-top: 0.75rem !important">
    <b>{{signer.name}}  {{signer.surname}} 
    </b>&nbsp;
 </div>
 </div> 
 <div class="form-row" >      
     <div class="col-md-4">
           <ng-select #mailDocumentSelect 
                  formControlName="mailSigner" [items]="mails"
                  bindValue="code" bindLabel="description"  
                  (click)="getMails()">
            </ng-select>
  </div>
   <div class="col-md-4">
                                <ng-select>
                                </ng-select>
  </div>
                    </div>
                    <br>   
                </div>

where "signers" is a list that gets populated by a click event to create a list of select mail options.

The issue arises when attempting to ensure that ALL "mailSigner" form control fields have a value.

I've created a function triggered by another button click:

 getCompiledFeq(){

  if(this.availableSigners.get('mailSigner').value){
     return true;
  }
  return false;
 }

However, this function currently returns true as long as there is at least one selected value (not validating all form controls).

How can I implement validation to check that every select form field is filled?

Answer №1

It is crucial to ensure that each form control has a unique name, otherwise conflicts may arise.

To differentiate between form controls, you can use an index.

In your TypeScript file, iterate through all the signers and assign a unique ID for each signer in the form of:

this.availableSigners = new FormGroup({
    nameSigner: new FormControl(),
    mailSigners: new FormArray()
});

for (let i = 0; i < signers.length; i++) {
    this.availableSigners.get('mailSigners').push('mailSigner-' + i , new FormControl('', Validators.required));
}

Additionally, update the formControlName in your HTML file to "mailSigner-{{i}}" to maintain a unique index.

<div *ngFor="let signer of signers; let i = index">
    <div class="form-row">
        <div class="card-body col-md-4" style="padding-top: 0.75rem !important">
            <b>{{signer.name}} {{signer.surname}}</b>&nbsp;
        </div>
    </div>
    <div class="form-row">      
        <div class="col-md-4">
            <ng-select #mailDocumentSelect formControlName="mailSigner-{{i}}" [items]="mails" bindValue="code" bindLabel="description" (click)="getMails()">
            </ng-select>
        </div>
        <div class="col-md-4">
            <ng-select>
            </ng-select>
        </div>
    </div>
    <br>   
</div>

Answer №2

Why not implement the use of Validators and designate nameSigner as a mandatory field? Your FormGroup will only be considered valid if all FormControls with a required Validator are filled.

To make the control required:

this.availableSigners = new FormGroup({
        nameSigner: new FormControl('', Validators.required),
        mailSigner: new FormControl()
});

Check if every field has a value:

getCompiledFeq(){

  if(this.availableSigners.valid){
     return true;
  }
  return false;
 }

Refer to Angular Documentation for more information on Validators: https://angular.io/guide/form-validation#reactive-form-validation

Answer №3

When setting up your forms, it is important to initially set nullValidator as suggested, and then mark them as required.

//Include this in your TypeScript file and verify
   get form() { return this.availableSigners.controls }

Make sure to add the following code snippet to check if the form is valid:

 if(this.availableSigners.valid){
     return true;
  }
else{
for(let i in this.availableSigners.controls){
  this.availableSigners.controls[i].markAsTouched();
}
}
 }

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

Adjust the pagination page size based on the value in the Angular scope dynamically

My goal is to provide the user with the ability to adjust the number of rows displayed in a table. This feature is crucial for our web app, as it needs to be accessible on various devices and should allow users to customize their viewing experience to redu ...

Steps for extracting URL parameters from AWS API Gateway and passing them to a lambda function

After successfully setting up my API gateway and connecting it to my lambda function, I specified the URL as {id} with the intention of passing this parameter into the lambda. Despite numerous attempts using both the default template and a custom one for ...

Receiving a 401 error when making an Axios post request

Having trouble with a 401 error when making a POST request to an API? Don't worry, I've got some suggestions that might help. I'm able to successfully make GET requests to the same API with a 200 status, so it could be a syntax issue in the ...

Unable to execute the new firebase on node server

I'm currently watching this google talk. However, I am facing an issue trying to create a firebase object. Following my package.json file, I initiated with: npm install firebase --save Then proceeded with the following steps: let Firebase = requir ...

Unable to retrieve valid inputs from text fields by utilizing jQuery selectors

Extracting information from text fields is my goal. Specifically, these fields contain dates which consist of three parts: the year, month, and day. The dates are divided into two sections - the first date and the last date, serving as boundaries for a sea ...

Issue with table display within <div> element in React

Recently diving into React, I find myself in a situation where I need to display data in a table once it's ready or show 'Loading' if not. Currently, my render() function looks like this: return ( <div> { this.state.loaded ...

Adjust the color of a DIV based on the text value retrieved from an external source

I am looking to dynamically change the text color between red and green based on a numeric value received from an external source (API). If the value is greater than or equal to 50, it should be displayed in red. If it's less than 50, then it should ...

Adjusting the XHR 'Referer' header within a Chrome application

Is there a way to adjust the 'Referer' header in my Chrome app? When I try to set it using the following code: xhr.setRequestHeader('Referer', 'http://example.com/'); I receive an error message that says: ajax.js:15 Refused ...

Delete the child node that matches the specified variable

I am facing the challenge of removing a list item node if it matches a specific variable. For example If username is equal to User 1 And if a node is also User 1 Then I want to remove this particular node. Unfortunately, I have not been able to assign ID ...

A data structure that represents a tuple type including the object's keys as string literals

Consider the following interface: interface EPostageInsertExEvent_Parameter { readonly Doc: Word.Document; cpDeliveryAddrStart: number; cpDeliveryAddrEnd: number; readonly cpReturnAddrStart: number, readonly cpReturnAddrEnd: number; ...

Unexpected token "," in jQuery UI autocomplete error

Using the autocomplete feature works perfectly on my PC. However, I encounter an error when trying to test it on a mobile device. Do I need to utilize jQuery mobile in order for jQuery to function properly on mobile devices? Error message on line 3 of th ...

add a hyperlink within a mouse click action

Looking for a way to make phone numbers clickable on mobile devices? Check out this script! I've implemented a script that displays a phone number when users click 'call us' and sends a Google Analytics event. However, I'm having troub ...

Exploring the usage of asynchronous providers in NestJS

I am currently utilizing nestjs and I am interested in creating an async provider. Below is my folder structure: . ├── dist │ └── main.js ├── libs │ └── dma │ ├── src │ │ ├── client │ ...

Delivering objects from controller in AngularJS

I'm currently working on a project where I need to retrieve objects from the controller. Here's a snippet of my code: score.component.js: angular.module('score').component('score',{ templateUrl : 'app/score/score.t ...

What is the solution to setting true and false equal to true in an AngularJS expression?

How can I determine if an input field has been touched and is empty, without using the built-in functions in Angular? <form-input is-invalid-on="isTouched && !gs.data.name || gs.data.name.length > 50"></form-input> If isTouched &am ...

Angular reloads content when language is switched

I am facing an issue with my language selector and default pipes for number or currency format. Even after changing the language (e.g., from en-US to fr-FR), the thousands separator remains unchanged despite the correct updates in LOCALE_ID and TranslateSe ...

Performing a request following a POST operation within Postman

Currently, I am using a Post method on a URL which is expected to be written into a database. What I would like to do is create an "if" statement within the test tab in Postman to check the status of the response and then run a query to confirm that the ...

Encountering Axios errors while executing API calls at a high frequency

Recently, I have been facing some challenges with making API calls from localhost using axios in a loop. While it works smoothly at times, most often I encounter errors like: cause: Error: connect ECONNREFUSED ::1:8000 at TCPConnectWrap.afterConnect ...

Is it possible to make the v-toolbar-title fixed within a v-navigation-drawer using Vuetify?

Can the <v-toolbar-title> be fixed within a <v-navigation-drawer>? <v-card class="d-inline-block elevation-12"> <v-navigation-drawer hide-overlay permanent stateless height="440" value="true"> <v-toolbar color="whi ...

Tips for incorporating jQuery script in Selenium WebDriver using Java

After developing a custom script that I would like to integrate into another Selenium WebDriver script: $function() { $("pane1").hide(300); }); I am currently exploring methods to invoke this script within my Selenium Java code. ...