我是Angular的新手,我的单选按钮有问题。
我有一个字符串数组,我想用它来创建带有单选按钮的表单。我不知道数组的长度或内容 - 值来自外部服务。
如何使用Angular Component和html文件中的表单生成器来完成此操作?它可以是这样的吗?
问题-dto.ts
export class QuestionDto {
questionText: string;
questionOptions: string[];
}
quiz.component.ts
question: QuestionDto = new QuestionDto();
questionOptionsForm: any;
constructor(private quizService: QuizService,
private formBuilder: FormBuilder) { }
ngOnInit() {
this.initForm();
}
initForm() {
this.questionOptionsForm = this.formBuilder.group({
//INIT RADIO BUTTONS HERE
})
}
quiz.component.html
<div>
<p>
Answers
</p>
<form *ngIf="questionOptionsForm">
<div *ngFor="let option of question.questionOptions">
<label>
<input type="radio" class="form-control">
{{option}}
</label>
</div>
</form>
</div>
答案 0 :(得分:0)
您应该尝试FormArray https://alligator.io/angular/reactive-forms-formarray-dynamic-fields/
代码看起来像:
initForm() {
this.questionOptionsForm = this.formBuilder.group({
options: this.formBuilder.array([this.createOption()])
});
}
createOption():FormGroup {
return this.formBuilder.group({
name: '',
description: ''
});
}