Before I used forms validation everything worked and my radio button group html looked like this:
<div class="form-group row">
<label class="col-xs-6 col-form-label">{{getHalfScoresErrorsCount()}}</label>
<div class="col-xs-6">
<span *ngFor="let answer of gradingKey.halfScoresCountAnswers">
<label class="form-check-inline">
<input class="form-check-input" type="radio" (ngModelChange)="onChangeHalfScoresErrorsCount($event)"
[(ngModel)]="gradingKey.currentAnswer" [value]="answer">
{{answer.value}}
</label>
</span>
</div>
</div>
After implementing reactive forms it looked like this:
<div class="form-group row">
<label class="col-xs-6 col-form-label">{{getHalfScoresErrorsCount()}}</label>
<div class="col-xs-6">
<span *ngFor="let answer of gradingKey.halfScoresCountAnswers">
<label class="form-check-inline">
<input class="form-check-input" type="radio" (ngModelChange)="onChangeHalfScoresErrorsCount($event)"
formControlName="halfScoresCount" [value]="answer">
{{answer.value}}
</label>
</span>
</div>
</div>
I added the formControlName attribute and removed the ngModel directive...
Then I changed the code: GradingKeyComponent.ts:
ngOnInit()
{
this.gradingKeyForm = this.fb.group({
bestGradeScores: bestGradeScoresFormControl,
worstGradeScores: worstGradeScoresFormControl,
scoreAtBend: [this.gradingKey.scoreAtBend],
gradeAtBend: [this.gradingKey.gradeAtBend],
halfScoresCount: [this.gradingKey.currentAnswer]
});
}
I did NOT change my Model object: GradingKey.ts
constructor(obj: any)
{
this.halfScoresCountAnswers = [new KeyValue(true, 'Yes'), new KeyValue(false, 'No')];
this.currentAnswer = obj.halfScoresCount == true ? this.halfScoresCountAnswers[0] : this.halfScoresCountAnswers[1];
}
I would prefer not to change my html just because I need validation now... 2 concerns!
At the moment no radio buttons value is set as true/selected.
Some might say this is due to having 2 equal formControlName`s in the *ngFor...
How should I solve that correctly if possible without changing my html?
Once your relevant FormControl's (in this case,
halfScoresCount
)[value]
is set, the relevant radio option whoseanswer
matches should be automatically selected.I suspect this is due to initializing
as an array. It should probably be
where
this.graFodingKey.currentAnswer
matches a possible value ingradingKey.halfScoresCountAnswers[]
(more explicitly, matches a possible value for the iteratedanswer
s) exactly as you did before reactive forms (i.e.,[(ngModel)]="gradingKey.currentAnswer" [value]="answer"
)