I have a FormControl in my Angular 8 app like this:
this.closingOrderFormGroup = this._fb.group({
final_price: new FormControl('', [ Validators.required ] ),
});
I tried to add/remove Validators.required dynamically based on some radio button check as follows:
radioChange( event ) {
const finalPriceControl: any = this.closingOrderFormGroup.get('final_price');
if ( event.value == 'completed' ) {
finalPriceControl.setValidators([Validators.required]);
}
else if ( event.value == 'rejected' ) {
finalPriceControl.setValidators(null);
}
}
But after set Validators null the FormControl "status" is still Invalid. How should I change the FormControl status?
You can subscribe for value change in angular reactive form.
ngOnInit() {
this.loginForm = this.fb.group({
final_price: ['', [ Validators.required ] ]
});
this.formControlValueChanged();
}
//Subscribe this way
formControlValueChanged() {
const finalPriceControl = this.loginForm.get('final_price');
this.loginForm.get('final_price').valueChanges.subscribe(
(mode: string) => {
console.log(mode);
if (mode === 'completed') {
finalPriceControl.setValidators([Validators.required]);
} else if (mode === 'rejected') {
finalPriceControl.clearValidators();
}
finalPriceControl.updateValueAndValidity();
});
}
Hope this helps :)