Angular 4反应形式与复杂对象上的单选按钮绑定不起作用

时间:2017-07-20 20:07:18

标签: angular angular-forms

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

为什么它不起作用?

这在角4之前有效,见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>

组件

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

1 个答案:

答案 0 :(得分:1)

您可以将[checked]属性添加到无线电组,该属性可以是用于评估是否应检查无线电的语句。只要点击设置值,问题就是无法反映已更改数据的广播组,它可能适合您。

相关答案:https://stackoverflow.com/a/39407224/3934988

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

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