【发布时间】:2018-05-04 20:25:26
【问题描述】:
我在Dynamic Forms 上编辑了官方Angular.io 教程,以添加“数字”类型的表单控件/输入字段。
https://plnkr.co/edit/NslBCrFZLQnLblAqcmzV
NumberQuestion 类
import { QuestionBase } from './question-base';
export class NumberQuestion extends QuestionBase<string> {
controlType = 'numberbox';
type: string;
constructor(options: {} = {}) {
super(options);
this.type = options['type'] || '';
}
}
创建一个新的 NumberQuestion :
//...
new NumberQuestion({
key: 'years',
label : 'Years active',
type : 'number',
order : 4
})
模板:
<div [formGroup]="form">
<label [attr.for]="question.key">{{question.label}}</label>
<div [ngSwitch]="question.controlType">
<input *ngSwitchCase="'textbox'" [formControlName]="question.key"
[id]="question.key" [type]="question.type">
<input *ngSwitchCase="'numberbox'" [formControlName]="question.key"
[id]="question.key" [type]="question.type">
<select [id]="question.key" *ngSwitchCase="'dropdown'" [formControlName]="question.key">
<option *ngFor="let opt of question.options" [value]="opt.key">{{opt.value}}</option>
</select>
</div>
<div class="errorMessage" *ngIf="!isValid">{{question.label}} is required</div>
</div>
如果您单击“加载默认值”按钮,然后单击“保存”按钮,您将看到表单的值对象保留了 formControl 'Years active' 的数字类型。
但是,如果您首先在 'Years active' 控件中键入,然后点击保存,您会看到该值已转换为字符串。
我了解这是正常行为,如下所述: https://stackoverflow.com/a/35791893/2025271
我想知道是否有办法指示 Angular 的 FormControl 在访问它们的值时将数字类型输入保留为“数字”。
我知道我可以手动执行此操作,方法是使用 parseInt() 编辑更改值,但我正在尝试查找是否有内置方法来执行此操作。
【问题讨论】: