我有一些问题作出复选框采用了棱角分明4.如何管理Augular动态表单中的复选框?
火狐在一个动态的形式工作,选中复选框时,我得到的值代替true
'on'
。而取消选中时,该值仍然存在,并且未设置为false
或''
。
在Chrome,它甚至不似乎工作...
我已经创建的Angular dynamic form tutorial为例基地。
我加入了一个名为question-checkbox.ts
一个新的文件管理复选框:
import { QuestionBase } from './question-base';
export class CheckboxQuestion extends QuestionBase<boolean> {
controlType = 'checkbox';
type: string;
constructor(options: {} = {}) {
super(options);
this.type = 'checkbox';
}
}
然后,我已经更新了dynamic-form-question.component.html
使用这个新的类型:
<div [formGroup]="form">
<label [attr.for]="question.key">{{question.label}}</label>
<div [ngSwitch]="question.controlType">
<select [id]="question.key" *ngSwitchCase="'dropdown'" [formControlName]="question.key">
<option *ngFor="let opt of question.options" [value]="opt.key">{{opt.value}}</option>
</select>
<input *ngSwitchDefault [formControlName]="question.key" [id]="question.key" [type]="question.type" />
</div>
<div class="errorMessage" *ngIf="!isValid">{{question.label}} is required</div>
</div>
而且,我已经更新了dataset in question.service.ts
:
import { Injectable } from '@angular/core';
import { DropdownQuestion } from './question-dropdown';
import { QuestionBase } from './question-base';
import { TextboxQuestion } from './question-textbox';
import { CheckboxQuestion } from './question-checkbox';
@Injectable()
export class QuestionService {
getQuestions() {
let questions: QuestionBase<any>[] = [
new DropdownQuestion({
key: 'brave',
label: 'Bravery Rating',
options: [
{ key: 'solid', value: 'Solid' },
{ key: 'great', value: 'Great' },
{ key: 'good', value: 'Good' },
{ key: 'unproven', value: 'Unproven' }
],
order: 3
}),
new TextboxQuestion({
key: 'firstName',
label: 'First name',
value: 'Bombasto',
required: true,
order: 1
}),
new TextboxQuestion({
key: 'emailAddress',
label: 'Email',
type: 'email',
order: 2
}),
new CheckboxQuestion({
key: 'sideksick',
label: 'Sidekick',
order: 3
})
];
return questions.sort((a, b) => a.order - b.order);
}
}
最后,我有了日的dynamic-form.component.html
显示表单的当前状态:
<div>
<form [formGroup]="form">
<div *ngFor="let question of questions" class="form-row">
<df-question [question]="question" [form]="form"></df-question>
</div>
</form>
<p><strong>Current state</strong><br>{{form.value | json}}</p>
</div>
所以我的问题是:我应该怎么做才能够使用复选框的角4动态表单中,并能够获得正确的价值?
至于为什么我需要使用动态表单,这是因为我正在生成基于来自描述它的外部服务的JSON的表单。