Angular FormControl check if required

Sergey picture Sergey · Nov 30, 2018 · Viewed 22.5k times · Source

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?

Answer

SiddAjmera picture SiddAjmera · Nov 30, 2018

You can do something like this:

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, AbstractControl } from '@angular/forms';

@Component({...})
export class AppComponent  {
  form: FormGroup = new FormGroup({
    control: new FormControl(null, Validators.required)
  });

  get validator() {
    const validator = this.form.get('control').validator({} as AbstractControl);
    console.log(validator);
    if (validator && validator.required) {
      return true;
    }
  }
}

And then in your Template:

<form [formGroup]="form" (submit)="onSubmit()">
  Control: <span *ngIf="validator">*</span> <input type="text" formControlName="control">
  <button>Submit</button>
</form>

NOTE: Just get the form control as a type of AbstractControl using this this.form.get('control').validator({} as AbstractControl);

This will return an Object with the list of validators that are present on your FormControl. You can then check for the required key in the Object. If it exists and its value is true then you can be sure that a Required Validator is applied on the FormControl.


Here's a Working Sample StackBlitz for your ref.