Search code examples
angularvalidationform-controlangular-reactive-forms

Angular FormControl check if required


Is there a way to check whether control is required?

The problem arose when I implemented a dedicated form field component which accepts FormControl and has not only input but also validation errors. Since some field are required it's good to let the user know if it's required by *.

Is there a way to check the @Input() control: FormControl for Validators.required and display an asterisk?


Solution

  • According to this Angular documentaion you can use hasValidator method to check if a built-in validator is used in your control.

    let abstractControl = this.formGroup.controls[this.formControlName];
    const isRequired = abstractControl.hasValidator(Validators.required);