【发布时间】:2017-06-28 23:40:52
【问题描述】:
我在使用 Angular 4 使复选框以动态形式工作时遇到一些问题。
在 Firefox 上,选中复选框时,我得到的值是 'on' 代替 true。并且当取消选中它时,该值仍然存在并且没有设置为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>
而且,我已经更新了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>
所以我的问题是:我应该怎么做才能在 Angular 4 动态表单中使用复选框,并能够获得正确的值?
至于为什么我需要使用动态表单,那是因为我是基于来自描述它的外部服务的 JSON 生成我的表单。
【问题讨论】:
标签: angular