首页 > 解决方案 > Angular - 为表单控件中的输入类型编号设置默认值

问题描述

我正在尝试将输入类型编号的默认(初始)值设置为 1,但很难弄清楚如何去做。我知道value="1"如果没有,我可以设置值formControlName。我试过了inputNum: new FormControl(1, [Validators.required, Validators.pattern('^[1-9]\\d*$')])

inputNum: new FormControl([1, Validators.required, Validators.pattern('^[1-9]\\d*$')])没有成功。

输入的初始值应该是 1 但我应该能够将它设置为 1 到任何正整数。

 <input formControlName="inputNum" class="form-control" [ngClass]="{'is-invalid':inputNumForm.touched && inputNumForm.errors}" type="number">
    <div class="invalid-feedback" *ngIf="inputNumForm.touched && inputNumForm.errors">
       <label *ngIf="inputNumForm.errors.required">Numbers Only</label>
    </div>
  public form = new FormGroup({
    inputNum: new FormControl('', [Validators.required, Validators.pattern('^[1-9]\\d*$')]),
  });

  get inputNumForm(): FormControl {
    return this.form.controls['inputNum'] as FormControl;
  }

标签: angulartypescript

解决方案


 public form = new FormGroup({
    inputNum: new FormControl('1', [Validators.required, Validators.pattern('^[1-9]\\d*$')]),
 });

推荐阅读