What is the best way to dynamically assign formControlNames in Angular using *ngFor?

I am currently facing a challenge with setting form controls using *ngFor over objects in an Array. The number of objects in the array can vary, sometimes resulting in only 1 object while other times multiple objects are present.

My specific issue revolves around creating form control names dynamically within the loop and setting form group validators in the component. Simply defining them as shown below causes a problem - if there is only one object, the form remains invalid due to the absence of another formControlName that does not exist.

For instance, if the first object named "Days" is missing from the list, "Days" still exists in this.form and appears in controls:

Array:

indicators = [
  {name:"Days",data:[250,1]},
  {name:"Multiply Average",data:[3,.25,1]}
],

Component:

ngOnInit() {
    this.form = this._fb.group({
            "Multiply Average":['', Validators.compose([
                Validators.required
                ])],
            "Days":['', Validators.compose([
                Validators.required
                ])],
        });  
    };

Template:

<span
     *ngFor="let i of indicators">
          {{i.name}}: 
          <md-slider
            formControlName={{i.name}}
            color="primary"
            [max]=i.data[0]
            [thumb-label]="true"
            [step]=i.data[1]
            [min]=i.data[2]>
          </md-slider>
  </span>

If anyone has solutions or suggestions on how to address this dilemma, I would greatly appreciate any help provided.

Answer №1

Ensure that the [formGroup]="form" directive is added to your form element.

Additionally, for enhanced clarity, consider using property binding instead of interpolation with the formControlName attribute:

[formControlName]="i.name"

Answer №2

To achieve conditional validation, you need to customize the validators based on user choices. The following example illustrates this concept in a simple manner. For more complex scenarios with multiple fields and validations, I recommend referring to this resource: "How to implement conditional validation in Angular model-driven forms"

The basic idea involves setting a change event listener on the md-select element when the user selects an option. This event triggers a function that modifies the validators of another form control dynamically:

<md-select
  formControlName="indicator1"
  (change)="checkValue(form.get('indicator1'))">
  <md-option
      *ngFor="let indicator of indicators['indicatorlist']" 
       [value]="indicator">
       {{indicator}}
  </md-option>   
</md-select>

In the function checkValue(), we validate the selected value against a specific criterion. If the condition is met, we update the validators accordingly using setValidators() and then call updateValueAndValidity() method:

checkValue(ctrl) {
  if(ctrl.value != "Above WMA - Volume Price") {
    this.form.get('Multiply Average').setValidators(null);
    this.form.get('Multiply Average').updateValueAndValidity();
  } else {
    this.form.get('Multiply Average').setValidators(Validators.required);
    this.form.get('Multiply Average').updateValueAndValidity();
  }
}

You can also utilize clearValidators() instead of setValidators(null) for the same purpose.

This implementation provides a basic understanding of how conditional validation works. Feel free to explore the demo link below to see it in action:

DEMO: https://plnkr.co/edit/h4nQfg1VYykaGgfNfnWk?p=preview

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

Having trouble locating the module while importing MP3 files in a React project

UPDATE The issue stemmed from my limited understanding of the environment I was working in, but the responses provided below may be helpful for others facing similar challenges. EDIT: It appears that there is a problem with trying to import an mp3 file in ...

Ways to reuse test cases across different test suites in Protractor

There are some shared test cases that can be utilized across different test suites. For example, suppose suite x and suite y both require the same set of test cases to function properly. To address this, a separate .js file containing the shared code has ...

Issue encountered: Exceeded maximum call stack size while running npm start command for Angular

Encountering the 'Error: Maximum call stack size exceeded' while running ng serve Node version: v14.17.5 Npm version: 6.14.14 "dependencies": { "@angular-material-components/datetime-picker": "^5.1.0", " ...

Can the GitHub URL be utilized for installing TypeScript npm dependencies?

When working with an npm library written in TypeScript, the usual process involves writing the source code in TypeScript, pushing it to GitHub, then converting it to JavaScript and pushing the resulting JavaScript code to the npm repository. When adding ...

What is the best way to incorporate multiple Bootstrap templates into an Angular project without causing conflicts between them?

When incorporating a bootstrap template into the admin interface, it is important to consider that its design may vary from the template used for visitors. Mixing multiple styles based on different templates can lead to conflicting styles and can potenti ...

When executed, the Node application successfully compiles

I have a TypeScript application that runs smoothly in development mode using ts-node. However, after building the application, I encounter some unexpected warnings and errors. This is my tsconfig.json: { "compilerOptions": { "incremen ...

Error: Unexpected token 'export' in NextJS Syntax

A situation has arisen where a library that was functioning perfectly in an app utilizing react-create-app is now needed for use in NextJS (using npx create-next-app --ts). However, upon attempting to integrate the library, an error was encountered: erro ...

Using React hooks and Typescript: I was expecting to see an assignment or function call, but instead, an expression was

After working as a React developer for quite some time, my workplace recently introduced Typescript, which I am still getting familiar with. I implemented a custom hook for managing cookies, but the function it returns is generating an error. Here's ...

Ensure that you only run `npm publish` in the Angular monorepo if there

In my angular monorepo, I have an "app" and a library that is published as its own npm package. The publishing process is automated on a CI environment. Previously, the library and app had separate build jobs. Now that they are built together, I am encount ...

My inquiry was met with silence from the Angular project

I have encountered an issue with my dockerized angular project. Upon starting my container, it appears that the 4200 port is already in use, even though the CMD command within the container does not initiate the application startup. Here is how my Docke ...

Tips for correctly setting object initial values in React CreateContext

How can I correctly define the initial value of the constance trainsDetails in React Create Context? The trainsDetails is an object with various properties, fetched as a single object from an endpoint and has the values specified below in the TrainsDetails ...

Preventing driver closure during test suites in Appium/Webdriverio: a step-by-step guide

Currently, I am in the process of testing a react native application with a specific test suite and test cases. The test case files I am working with are: login.ts doActionAfterLogin_A.ts Test Suite: [login.ts, doActionAfterLogin_A.ts] Issue at Hand: W ...

Customize ngx-select dropdown by adding unique styles to items for a personalized display

Struggling to showcase dropdown items using ngx-select with personalized design. The dropdown items are arrays of different components (each with unique styling). Any tips on how to make this happen? View my code selectDropdown ...

The error message "Property 'showUserDropdown' is not found on type '{}'.ts" indicates that the specified property is not present in the defined

While creating a basic Vue component, I encountered an error in the IDE regarding the {{ showUserDropdown }} with the message: Property 'showUserDropdown' does not exist on type '{}'.ts Despite adding it to data, <template> &l ...

Unable to determine all parameters for Modal: (?, ?, ?)

import { Component, Inject } from '@angular/core'; import { NavController, Modal } from 'ionic-angular'; import { PopupPage } from '../../components/modal/modal.page'; @Component({ templateUrl: 'build/pages/spot/spot. ...

An issue has been identified: the element 'insight-dashboard-erneuerung-settings' is unrecognized during the implementation of lazy loading

I am currently working on implementing lazy loading for the Dashboard module in my Angular project, but I have run into an issue: When trying to use 'insight-dashboard', I am getting the error message 'is not a known element'. I have c ...

Personalizing Dialog Title in material-ui

While delving into the world of React and Material-UI, I encountered a challenge in updating the font color in the DialogTitle component. After browsing through various resources, I came across a helpful link that suggested overriding the dialog root class ...

The request.files property in express-fileupload is consistently coming back as undefined

I am trying to achieve the task of uploading a file from my browser and sending it via POST to an Express.js application, which will then download the file using express-fileupload. Here is the client-side JavaScript code I have written so far: // Triggere ...

Can Ansible and Pulumi be integrated to work together effectively?

Is it possible to create multiple DigitalOcean droplets in a loop and then use Ansible to configure software and security measures on them, similar to how Terraform works? If so, what would the JavaScript/TypeScript code for this look like? I couldn' ...

I am attempting to incorporate a List View within a Scroll View, but they are simply not cooperating. My goal is to display a collection of items with additional text placed at the bottom

This is how it should appear: item item item item additional text here I am trying to create a layout where the list is in List View for benefits like virtual scrolling, but the entire layout needs to be within a Scroll View. I want to be able to con ...