我是基于JSON动态生成HTML表单。我使用的是此处提供的官方示例:https://angular.io/guide/dynamic-form
我正在尝试扩展此示例以在我的动态表单中添加其他控件(textarea,单选按钮,复选框等)。我已经能够实现所有控件,复选框除外。虽然该复选框在屏幕上可见,但该值不会以其封闭形式捕获。
我的Checkbox定义如下:
import { QuestionBase } from './question-base-model';
export interface Values{
label: string;
value: string;
isChecked: boolean;
}
export class CheckBoxQuestion extends QuestionBase<boolean> {
controlType = 'checkbox';
options: Values[] = [];
constructor(options: {} = {}) {
super(options);
this.options = options['options'] || [];
}
}
我的JSON for checkbox是这样的:
{
key: 'sideDish',
label: 'Side dish',
type: 'checkbox',
order: 10,
name: 'sides',
options: [
{value: 'fries', isChecked: true, label: 'French Fries'},
{value: 'cheese', isChecked: false, label: 'Cheese'},
{value: 'sauce', isChecked: true, label: 'Tomato Sauce'}
]
}
我的动态HTML模板如下:
<div [formGroup]="form" >
<label [attr.for]="question.key">{{question.label}}</label>
<div [ngSwitch]="question.controlType">
<!-- Checkbox -->
<div *ngSwitchCase="'checkbox'">
<span *ngFor="let opt of question.options; let i = index">
<input type="checkbox"
[formControlName]="question.key"
[id]="i+'_'+question.key"
[value]="opt.value">
<label [attr.for]="i+'_'+question.key">{{opt.label}}</label>
</span>
</div>
</div>
FormControl代码如下所示(此处未对原始示例进行编辑):
toFormGroup(questions: QuestionBase<any>[] ) {
let group: any = {};
questions.forEach(question => {
let validatorsArray = [];
if(question.required) validatorsArray.push(Validators.required);
group[question.key] = validatorsArray.length > 0 ? new FormControl(question.value || '', Validators.compose(validatorsArray)) : new FormControl(question.value || '');
});
return new FormGroup(group);
此方法在init函数中使用:
ngOnInit() {
this.form = this.qcs.toFormGroup(this.questions);
}
当我点击“提交”按钮时,我正在打印&#34; form.value&#34;。使用我在表单中设置的值来休息所有控件打印件。但是,一个空字符串作为此复选框的值。我做错了什么?
提前致谢!