does someone know a way to find out for an Angular2 FormControl if the required validor is registered for the control.
this.form = builder.group({name: [\'\'
While there is no Angular API to directly find if the required
validator is set for a particular field, the roundabout way to achieve this is like as below:
import { NgForm, FormControl } from '@angular/forms';
const isRequiredControl = (formGroup: NgForm, controlName: string): boolean => {
const { controls } = formGroup
const control = controls[controlName]
const { validator } = control
if (validator) {
const validation = validator(new FormControl())
return validation !== null && validation.required === true
}
return false
}
I have tested this and this triggers only if the Validator.Required
validator is added to the particular FormControl
.