简体   繁体   中英

Reactive forms: Angular formarrays and formcontrols

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.

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>    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM