Home > Net >  How do i iterate over the input field names and values in Angular?
How do i iterate over the input field names and values in Angular?

Time:05-02

I am creating a form controls dynamically based on the dynamic data for the below model

{"name": "firstName"},
{"name": "lastName" }

<form [formGroup]="myForm" #formDirective="ngForm" >
    <div *ngFor="let n of data">
                <mat-form-field appearance="outline" >
                  <mat-select required [(value)]="selected" name="{{n.name}}">
                    <mat-option value="equal" >Equals</mat-option>
                    <mat-option value="notequal">Not Equals</mat-option>
                  </mat-select>
                </mat-form-field>
        
                <mat-form-field appearance="outline">
                  <input matInput name="{{n.name}}"> 
                </mat-form-field> 
    </div>
</form>

i want to send this dynamic data for which i need to iterate over the fields and get the name and value of the field.

i tried the below code, but no luck.. can someone please help me

myForm: any;
this.myForm = this.formBuilder.array([]); 
    Object.keys(this.myForm.controls).forEach((name) => {
          let currentControl = this.myForm.controls[name];
    
            console.log("name: "   name, "value: "  currentControl.value);
        });

CodePudding user response:

When you use the formBuilder you can use this.formBuilder.group(), something like:

args;
myForm;

startFormGroup(args){
   this.args = args;
   let aux = {};
   for(let arg of args){
      aux[arg] = new FormControl('');
   }
   myForm = this.formBuilder.group(aux);
}

Then, in the html you can use something like:

<form [formGroup]="form.form" #formDirective="ngForm">
   <div *ngFor="let arg  of args">    
        <mat-form-field appearance="outline">
          <input matInput name="{{arg}}" formControlName="{{arg}}"> 
        </mat-form-field> 
    </div>
 </form>

Please note, that this is a template and I have not tested the code.

See my answer to this question for another similar example.

Fell free to ask for clarification if needed.

  • Related