Title: How to make a dynamic question answer form using formArray in angular 6
Tags: angular;formarray
Question: I am trying to make a form which contains a question and some options for that as answers. Adding Options are dynamic, so I'm trying to implement it using formArray.
But at the same time, I need to save which option is correct, so for that, I'm using radio buttons with each option.
Problem is when I'm changing the radio button it doesn't uncheck previous ones.
<form [formGroup]="questionForm"&gt;
<button type="button" class="iconBtn" title="Add Options" (click)="addOptions()"&gt;
Add Option
</button&gt;
<div formArrayName="options"&gt;
<div *ngFor="let option of questionForm.controls['options'].controls; let i = index"&gt;
<div class="row" [formGroupName]='i'&gt;
<div class="col-xs-1 text-right"&gt;
<span class="radio"&gt;
<label class="radio-inline" title="Select if this is correct answer"&gt;
<input type="radio" [formControlName]="'isCorrect'" value="1" (change)="selectCorrectOption($event)"/&gt;
</label&gt;
</span&gt;
</div&gt;
<div class="col-xs-11"&gt;
<input type="text" class="form-control" placeholder="Option Text" [formControlName]="'optionText'"/&gt;
</div&gt;
</div&gt;
</div&gt;
</div&gt;
</form&gt;
TypeScript (ts):
ngOnInit() {
this.questionForm = this._fb.group({
'options': this._fb.array([
this._fb.group({
'isCorrect': [0],
'optionText': ['']
})
])
public addOptions() {
let control = < FormArray &gt; this.questionForm.controls.options;
control.push(this._fb.group({
'isCorrect': [0],
'optionText': ['']
})
Any Solution would be appreciated.


Here is another answer: You have to add name property in <input type="radio"&gt;

Here is another answer: you have to change your template code to have the same formControlName for every radio button like:
<input type="radio" formControlName="isCorrect" value="1" /&gt;
<input type="radio" formControlName="isCorrect" value="0" /&gt;
<input type="radio" formControlName="isCorrect" value="0" /&gt;
and access the value via
questionForm.value.isCorrect
I found that adding the name attribute to the radio button tag is enough to meet the need of only having one button selected.
<input type="radio" name="isCorrect" formControlName="isCorrect" (change)="selectCorrectOption($event)"/&gt;

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2019:00:08/09/19', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<angular><formarray>', 'Title': 'How to make a dynamic question answer form using formArray in angular 6', 'ViewCount': 605, 'id': 57428461, 'user_AboutMe': '<p>Experienced in Developing Product based Responsive Web and Mobile Apps development using Angular and React.</p>\n', 'user_AccountId': 5904729.0, 'user_DisplayName': 'OM PRAKASH', 'user_Reputation': 403.0, 'user_Views': 67.0, 'user_id': 4646944.0}}