【问题标题】:Is there a way to create a 'number' input FormControl in Angular 2 Reactive Forms有没有办法在 Angular 2 Reactive Forms 中创建一个“数字”输入 FormControl
【发布时间】: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() 编辑更改值,但我正在尝试查找是否有内置方法来执行此操作。

【问题讨论】:

    标签: forms angular input


    【解决方案1】:

    我设法通过在表单值前加上加号并分配给临时变量来修复它。

    let myNumber : number = + this.form.value.myNumber;
    

    【讨论】:

      【解决方案2】:

      作为您问题的替代动态解决方案:

      • 您可以创建一个包含表单值的对象,我在代码中将其称为myObject
      • 在提交时调用createMyObject() 方法一一获取您的问题
      • 然后检查其类型是否为number
        • 如果是数字,则向对象添加number 属性,其中key 是问题的关键,value 是问题的值formControl ,然后将属性添加到 myObject
        • 否则您创建一个string 属性并将其添加到myObject

      DynamicFormComponent的Ts代码

      import { Component, Input, OnInit }  from '@angular/core';
      import { FormGroup }                 from '@angular/forms';
      
      import { QuestionBase }              from './question-base';
      import { QuestionControlService }    from './question-control.service';
      
      @Component({
        selector: 'app-dynamic-form',
        templateUrl: './dynamic-form.component.html',
        providers: [ QuestionControlService ]
      })
      export class DynamicFormComponent implements OnInit {
      
        @Input() questions: QuestionBase<any>[] = [];
        form: FormGroup;
        payLoad = '';
        myObject : any = {};
      
        createMyObject(){
          for(let question of this.questions){
            let key = question.key;
            if(question.type === "number"){
              let tempObj : number = +this.form.value[key];
              this.myObject[key] = tempObj;
            }
            else{
              let tempObj : string = this.form.value[key];
              this.myObject[key] = tempObj;
            }
          }
        }
      
        constructor(private qcs: QuestionControlService) {  }
      
        ngOnInit() {
          this.form = this.qcs.toFormGroup(this.questions);
        }
      
        onSubmit() {
          this.payLoad = JSON.stringify(this.form.value);
          this.createMyObject();
        }
      
        load(){
          this.form.patchValue({"firstName":"kratos","emailAddress":"kratos@gow.com","brave":"solid","years":132});
        }
      }
      
      
      /*
      Copyright 2017 Google Inc. All Rights Reserved.
      Use of this source code is governed by an MIT-style license that
      can be found in the LICENSE file at http://angular.io/license
      */
      

      HTML 代码动态表单组件:

      <div>
        <button type="button" (click)="load()">Load Defaults</button>
      
        <form (ngSubmit)="onSubmit()" [formGroup]="form">
      
          <div *ngFor="let question of questions" class="form-row">
            <app-question [question]="question" [form]="form"></app-question>
          </div>
      
          <div class="form-row">
            <button type="submit" [disabled]="!form.valid">Save</button>
          </div>
        </form>
      
        <div *ngIf="payLoad" class="form-row">
          <strong>Saved the following values</strong><br>{{payLoad}}
        </div>
      
        <div *ngIf="payLoad" class="form-row">
          <strong>Saved the following values</strong><br>{{myObject | json}}
        </div>
      </div>
      

      希望这会有所帮助:)

      【讨论】:

      • 非常感谢,但我已经做了一些非常相似的事情。我正在寻找一种内置的方法,如果存在的话。
      • 我不认为您的问题存在内置方式,因为数字输入被视为文本输入,作为另一种解决方案,您可以创建一个包含数字输入的自定义组件,但是它返回一个整数作为值
      猜你喜欢
      • 2023-03-04
      • 2018-02-07
      • 2021-10-23
      • 2013-08-02
      • 1970-01-01
      • 2021-02-27
      • 2018-06-02
      • 1970-01-01
      • 2012-01-10
      相关资源
      最近更新 更多