Pascal
Pascal

Reputation: 12885

Angular 4 reactive forms with radio button binding on complex object does not work

The gradingKey.currentAnswer is not bound to the radio button when the value is initially added to the form.

why does it not work?

This worked once before angular 4 see: How to set the selected radio button initially in *ngFor on radiobutton group

HTML

<form [formGroup]="gradingKeyForm">

<div class="form-group row">
<label class="col-6 col-form-label">{{getHalfScoresErrorsCount()}}</label>
<div class="col-6">
<span *ngFor="let answer of gradingKey.halfScoresCountAnswers">
    <label class="radio-inline">
        <input type="radio" (ngModelChange)="onChangeHalfScoresErrorsCount($event)"
        formControlName="halfScoresCount" [value]="answer">
        {{answer.value}}
     </label>
</span>
</div>
</div>
</form>

Component

 ngOnInit() {

    this.gradingKeyForm = this.fb.group({       
      halfScoresCount:   this.gradingKey.currentAnswer,
     });
}

Model

import KeyValue from '../keyvalue';
import { IGradingKey } from './shared/grading-key-interface';

export default class GradingKey implements IGradingKey {

  halfScoresCountAnswers: KeyValue<boolean, string>[];
  currentAnswer: KeyValue<boolean, string>;

  constructor(obj: any) {
    this.halfScoresCountAnswers = [new KeyValue(true, 'Ja'), new KeyValue(false, 'Nein')];
    this.currentAnswer = obj.halfScoresCount == true ? this.halfScoresCountAnswers[0] : this.halfScoresCountAnswers[1];
   }
}

Upvotes: 0

Views: 1920

Answers (1)

chairmanmow
chairmanmow

Reputation: 650

You can added a [checked] property to the radio group which can be a statement to evaluate whether the radio should be checked or not. As long as clicking is setting the values, and the issue is the radio group not reflecting the data that was changed, it'll probably work for you.

Relevant answer: https://stackoverflow.com/a/39407224/3934988

So assuming your code works as it should everywhere else, something like this should work :

  <input type="radio"      (ngModelChange)="onChangeHalfScoresErrorsCount($event)"
    formControlName="halfScoresCount" [value]="answer" [checked]="answer === currentAnswer">

Upvotes: 1

Related Questions