Angular 4 个带有单选按钮绑定到复杂对象的反应式表单不起作用

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

最初将值添加到表单时,gradingKey.currentAnswer 未绑定到单选按钮。

为什么不起作用?

这在 angular 4 之前工作过一次:

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>

组件

 ngOnInit() {

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

型号

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];
   }
}

你可以在单选组中添加一个[checked] 属性,它可以是一个语句来评估单选是否应该被检查。只要点击设置值,并且问题是无线电组没有反映已更改的数据,它可能对您有用。

相关回答:

因此,假设您的代码在其他任何地方都可以正常工作,那么这样的事情应该可以工作:

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