Reputation: 1354
I have <mat-select required formControlName="registrationType">
If I select unregistered two input fields will be disabled, else it will be enabled. For that I used
const registrationType = this.practiceForm.get('registrationType')
registrationType.valueChanges.subscribe((value) => {
if(value === 'Unregistered'){
this.form.controls['registrationDate'].disable()
this.form.controls['registrationNumber'].disable()
}else if(value === 'registered') {
this.form.controls['registrationDate'].enable()
this.form.controls['registrationDate'].enable()
}
})
The two input fields get disabled as expected when I selected unregistered, but once I click save, the following error: Must supply a value for form control with name: 'registrationDate'
The formGroup
registrationType: new FormControl(null, Validators.required),
registrationDate: new FormControl(null, Validators.required),
registrationNumber: new FormControl(null, Validators.required),
I need help in fixing this. Thank you
Upvotes: 0
Views: 743
Reputation: 441
You could just disable the validators in the code you have like:
this.form.controls[""].validator = null;
Or you coould use on the form input the disabled attribute:
<input [disabled]="some_calculated_property">
Should be recognized by angular that's disabled, cause if you manipulate trough code like subscribe to input there won't be standard events that's going to be fired.
Upvotes: 1
Reputation:
Your validation requires you to have a required
value in your date.
If you disable fields, the form.value
doesn't contain the disabled fields.
This means your form is rendered invalid.
To avoid that, remove the validators along with the value :
if(value === 'Unregistered'){
this.form.controls['registrationDate'].disable()
this.form.controls['registrationNumber'].disable()
this.form.controls['registrationDate'].setValidators([])
this.form.controls['registrationNumber'].setValidators([])
} else if(value === 'registered') {
this.form.controls['registrationDate'].enable()
this.form.controls['registrationDate'].enable()
this.form.controls['registrationDate'].setValidators([Validators.required])
this.form.controls['registrationNumber'].setValidators([Validators.required])
}
Upvotes: 1