Angular Reactive form setValue setting string to number input type, input box empty but string value is assigned in controlls, validation required is not working
This is Form Controller
ngOnInit() {
this.profileForm = new FormGroup({
name: new FormControl("", Validators.required),
age: new FormControl("", Validators.required),
}
}
patchAge(){
this.profileForm.controls["age"].setValue("somethingString");
}
This is template
<form [formGroup]="profileForm" (ngSubmit)="onFormSubmit()">
<input
type="text"
formControlName="name"
/>
<input
type="number"
formControlName="age"
/>
</form>
The only validator your
age
control has isrequired
, which means the value cannot be empty, so the value can be anything.Even though you are setting the input as
type=number
, this is just a HTML validation, you are expecting your form object to be aware of this.That's why your form valid state is TRUE, because it has indeed a value.
So the solution for this will be to add another validation to
age
If you print right from the beginning the valid state of your form, it should be
false