【发布时间】:2020-11-24 18:23:23
【问题描述】:
我在父 formGroup 中有一个 formControl(收音机)并想在 formArray 中使用它。用例是 MCQ 问题有多个选项 (formArray),希望每个选项都有单选按钮来选择正确答案(只有一个)
JS
private createForm() {
this.form = new FormGroup({
question: new FormControl('', Validators.required),
correctOption: new FormControl(false),
options: new FormArray([this.newOption(), this.newOption()])
});
}
private newOption(): FormGroup {
const validators = [Validators.required];
return new FormGroup({
value: new FormControl('', validators),
explanation: new FormControl('')
});
}
HTML
<div [formGroup]="form">
<div formArrayName="options">
<div *ngFor="let option of form.get('options')['controls']; let idx = index">
<div class="form-group" [formGroupName]="idx">
<div class="input-group" style="align-items: center">
<textarea class="form-control" id="text" placeholder="" formControlName="value" autosize
id="option_{{idx}}"></textarea>
<span class="input-group-append">
<button class="btn btn-primary" type="button" (click)="removeOption(idx)" tabindex="-1"><i
class="fas fa-trash" aria-hidden="true"></i></button>
</span>
<span class="input-group-append ml-2 fas">
<input id="answer_option_{{idx}}" name="correctOption" type="radio" value="{{idx}}"
formControlName="<How to use parent form control correctOption?>" />
</span>
</div>
<div>
<ckeditor [editor]="editor" formControlName="explanation"
[config]="{ placeholder: 'Enter explanation' }">
</ckeditor>
</div>
</div>
</div>
</div>
</div>
【问题讨论】:
-
你能创建一个 StackBlitz 吗?
-
@AndreiGătej stackblitz.com/edit/angular-ivy-bimunj
-
谢谢,但我现在不确定您要达到的目标。你能详细说明一下吗?
-
如果你看到stackblitz,我想从2个选项中选择正确的答案选项,所以我使用了单选按钮,问题是单选按钮的表单控件在表单中处于根级别,并且选项是formarray,那么在formarray里面,我们如何使用根级的formcontrolname呢?如果有其他方法可以告诉我。
-
为什么需要使用
root level formcontrolname?
标签: javascript angular angular-reactive-forms