【问题标题】:Angular 4 reactive forms with radio button binding on complex object does not workAngular 4 反应形式与复杂对象上的单选按钮绑定不起作用
【发布时间】:2017-12-26 17:10:51
【问题描述】:

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

为什么它不起作用?

这在 angular 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];
   }
}

【问题讨论】:

  • 你能创建一个 plunker,因为我不会在这里使用checked,并且有一个 plunker 可以帮助。目前没有足够的代码来重现该问题。
  • 那么...您是否已经尝试使用上述代码重现“错误”?实际上一切都在那里需要什么。我可以稍后创建一个 plunkr...

标签: angular angular-forms


【解决方案1】:

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

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

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

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

【讨论】:

  • checked 属性真的应该与响应式表单一起使用吗?
  • 酷,如果它对你有用,你可能想接受答案,因为它在评论部分得到了一点点批评,但你似乎知道如何使用堆栈溢出,所以我会离开由你决定。
猜你喜欢
  • 2017-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-04
  • 2019-02-23
  • 1970-01-01
  • 2019-05-13
  • 2016-05-21
相关资源
最近更新 更多