【问题标题】:Angular Reactive form setValue setting string to number input type, input box empty but string value is assigned in controllsAngular Reactive表单setValue将字符串设置为数字输入类型,输入框为空但在控件中分配了字符串值
【发布时间】:2022-11-10 03:41:18
【问题描述】:

Angular Reactive form setValue将字符串设置为数字输入类型,输入框为空但在控件中分配了字符串值,所需的验证不起作用

这是表单控制器

    ngOnInit() {
       this.profileForm = new FormGroup({
         name: new FormControl("", Validators.required),
         age: new FormControl("", Validators.required),
       }
    }

    patchAge(){
      this.profileForm.controls["age"].setValue("somethingString");
    }

这是模板

<form [formGroup]="profileForm" (ngSubmit)="onFormSubmit()">
    <input
      type="text"
      formControlName="name"
    />
    <input
      type="number"
      formControlName="age"
    />
</form>

【问题讨论】:

    标签: angular angular-reactive-forms angular-formbuilder


    【解决方案1】:

    您的age 控件拥有的唯一验证器是required,这意味着该值不能为空,因此该值可以是任何值。

    即使您将输入设置为type=number,这只是一个 HTML 验证,您希望您的表单对象知道这一点。

    patchAge(){
      this.profileForm.get("age")?.patchValue("somethingString");
      console.log('Is my form valid?: ', this.form.valid) // TRUE
    }
    

    这就是为什么您的表单有效状态为 TRUE 的原因,因为它确实有一个值。

    因此,解决方案是向age 添加另一个验证

    age: new FormControl("", [
      Validators.required, 
      Validators.pattern(/^d+$/) // only numbers
    ]),
    

    如果您从一开始就打印表单的有效状态,它应该是false

    【讨论】:

      【解决方案2】:

      尝试在 ngOnInit() 上将“”更改为 0,如下所示 age: new FormControl("", Validators.required)age: new FormControl(0, Validators.required)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-03
        • 2021-12-21
        • 2011-05-19
        • 1970-01-01
        • 2018-08-09
        • 2019-01-27
        相关资源
        最近更新 更多