1

Let's say that I have 2 arrays

arraynames['Dog', 'Cat', 'Donkey', 'Bird'];
nrofanimals['10','15', '20', '25'];

These two arrays is defined right now for simplicity but in reality can be changed to other values and so on. The only constrain is that both of the arrays must have the same size. What I want is that I want to create a formcontrol for the amount of animals for each name. What I mean is I want in my localhost:4200 to show a mat-form-field with mat-label "Dog" with mat-input "10", and another mat-form-field with mat-label "Cat" with mat-input "15" and so on. How can I do that? Keep in mind that I give these two arrays as example only. In my case the arrays will be populated by the user so I cannot have predefined arrays. Thanks in advance.

1 Answer 1

1

Checkout Angular Dynamic Forms, FormArray and FormGroup to understand the basic concept required for your usecase.

A basic Proof of concept will be as following:

import { Component, Input } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
    
@Component({
  selector: 'app-animals',
  templateUrl: './dynamic-form-question.component.html'
})

export class AnimalsComponent {
  
  animalForm: any; 

  constructor(){
    const formControls = {};
      arraynames.forEach((animal,index)=>{  //iterate over your animal's array
        formControls['animal'] = new FormControl(nrofanimals[index]); //create a new form control for each animal and set the value of formcontrol via index from no array
        });
        this.animalForm = formControls; //assign the object to the formGroup variable 
      }
  }
}    

Then create your html template and iterate on your animal names' array, setting the animal name as formControlName, that way you will get your fields dynamically generated;

<form  [formGroup]="animalForm"> 
    
   <div *ngFor="let animal of arraynames;">
       <mat-form-field>
           <label>{{animal}}</label>
           <input  [formControlName]="animal">      
        <mat-form-field>
    </div>
    
    <div class="form-row">
        <button type="submit">Save</button>
    </div>

</form>    
Sign up to request clarification or add additional context in comments.

2 Comments

hi, be careful in your component you cannot call this.formControls since it's a const in your forEach loop
@Twen thanks for pointing out, I first declared it at component level but then moved it to constructor. Updated the answer now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.