我在 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”控件中输入,然后点击 Save,您将看到该值已转换为字符串。
我了解这是正常行为,如下所述:
https://stackoverflow.com/a/35791893/2025271
我想知道是否有一种方法可以指示 Angular 的 FormControl 在访问它们的值时将数字类型输入保留为“数字”。
我知道我可以手动执行此操作,通过使用 parseInt() 来编辑更改时的值,但我正在尝试查找是否有内置的方法来执行此操作。
最佳答案
我设法通过在表单值前面加上加号并分配给临时变量来修复它。
let myNumber : number = + this.form.value.myNumber;
关于forms - 有没有办法在Angular 2 Reactive Forms中创建 'number'输入FormControl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47411984/