Angular 7 FormControl将输入从数字转换为字符串

时间:2019-07-16 09:31:49

标签: forms angular7 angular-forms

我有一个FormGroup,其中定义了以这种方式使用的FormControl:

myForm: FormGroup = new FormGroup({ 
    ...
    code: new FormControl('', Validators.pattern('^[0-9]*$')),
    ...
  });

html:

<mat-form-field class="col">
                <input formControlName="code" matInput>
              </mat-form-field>

我希望此输入为数字,但无法正确转换。我已经注册了表单控件的vauleChanges事件,并执行了以下操作:

this.myForm.controls['code'].valueChanges.subscribe(d => {
     if(this.myForm.controls['code'].valid){
      this.myForm.get('code').setValue( +this.myForm.controls['code'].value);
      }
    })

我也尝试过使用as number<number>来转换值,但是如果我打印表单的值,则会将其打印为字符串而不是数字。
另外,加载页面时,我的输入显示默认值为0: enter image description here

但是我没有在任何地方设置0,也不想显示它。
我尝试将输入类型指定为数字,但是它显示了箭头,但我不希望它们显示。

enter image description here

实现此目的的正确方法是什么?我很困惑。

1 个答案:

答案 0 :(得分:0)

解决方案:

您只需检查模型(ngModelChange)=“ validate()” 中的更改,即可检查 validate()方法。

HTML文件:

<meta>

TS文件:

<input id="code" class="form-control" [(ngModel)]="code" required (ngModelChange)="validate()">

<div *ngIf="codeValidator.invalid" class="alert alert-danger">
    <div *ngIf="codeValidator.errors.required">
        Field must not be empty.
    </div>
    <div *ngIf="codeValidator.errors.pattern">
        Only numeric values are allowed.
    </div>
</div>

<input type="text" [(ngModel)]="numberValue">