之前我使用表单验证一切正常,我的单选按钮组html看起来像这样:
<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>
实施反应式表单后,它看起来像这样:
<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>
我添加了 formControlName 属性并删除了 ngModel 指令......
然后我更改了代码: 的 GradingKeyComponent.ts :
ngOnInit()
{
this.gradingKeyForm = this.fb.group({
bestGradeScores: bestGradeScoresFormControl,
worstGradeScores: worstGradeScoresFormControl,
scoreAtBend: [this.gradingKey.scoreAtBend],
gradeAtBend: [this.gradingKey.gradeAtBend],
halfScoresCount: [this.gradingKey.currentAnswer]
});
}
我没有更改我的Model对象: 的 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];
}
我宁愿不改变我的HTML只是因为我现在需要验证...... 2关注!
目前没有单选按钮值设置为true / selected。
有人可能会说这是因为* ngFor ...
中有2个相同的formControlName如果可能的话,如何在不更改我的HTML的情况下如何正确解决?
答案 0 :(得分:0)
一旦设置了相关的FormControl(在这种情况下,halfScoresCount
)[value]
,就应自动选择answer
匹配的相关广播选项。
我怀疑这是由于初始化
halfScoresCount: [this.graFodingKey.currentAnswer]
作为一个数组。应该是
halfScoresCount: this.graFodingKey.currentAnswer
其中this.graFodingKey.currentAnswer
与gradingKey.halfScoresCountAnswers[]
中的可能值匹配(更明确地,匹配迭代answer
的可能值)与反应形式之前完全匹配(即{{1} }})