1

I am attempting to add a radio button group to a FormArray. The issue is that when I select a value, it changes the value for every member of the FormArray. I know this has to do with the formControlName, but I don't know how to make the formControlName dynamic. I've looked at this post but it's 4 years old and a little vague; i.e., I couldn't come to a clear answer therefrom.

This is what I currently have:

TS component

//inputs and variable initialization

ngOnInit() {
  this.createSensorForm();
}

createSensorForm() {
    this.sensorForm = this.fb.group({
      ...
      definitions: this.fb.array([this.createDefinition()])
  });
}

createDefinition(): FormGroup {
  return this.fb.group({
    numeric: [""],
  });
}

addDefinition() {
  this.definitions = this.sensorForm.get('definitions') as FormArray;
  this.definitions.push(this.createDefinition());
}

HTML component

<form [formGroup]="sensorForm" (ngSubmit)="createSensor()">
  ...
  <div formArrayName="definitions" 
       *ngFor="let definition of sensorForm.get('definitions').controls; let i = index;">
    <div [formGroupName]="i">
      ...
      <input type="radio" [value]="true" 
             formControlName="numeric" [(ngModel)]="numeric"> Yes
      <input type="radio" [value]="false" 
             formControlName="numeric" [(ngModel)]="numeric"> No
    </div>
  </div>
    <button class="btn btn-primary" type="button" (click)="addDefinition()">
      <i class="fa fa-plus"></i> Add Definition
    </button>
</form>

1 Answer 1

1
<div *ngIf="sensorForm"  [formGroup]="sensorForm" (ngSubmit)="createSensor()>
  <!---first the name of array-->
  <div formArrayName="definitions">
      <!--after the loop using a div, this div has [fromGroupName]=i -->
      <div *ngFor="let definition of sensorForm.get('definitions').controls; 
                  let i = index;" [formGroupName]="i">
          <!--each element, only use formControlName, ¡NOT! [(ngModel)] -->
          <!-- ngModel is for Template driven Form  -->
          <input type="radio" [value]="true" formControlName="numeric" > Yes
          <input type="radio" [value]="false" formControlName="numeric" > No
      </div>
  </div>  
</div>

Your addDefinition is wrong, you have not "this.definitions"

addDefinition() {
    const definitions = this.sensorForm.get('definitions') as FormArray;
    definitions.push(this.createDefinition());
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Worked like a charm. Thanks a million!
be carefull, I update the answer adding the code to addDefinition

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.