Angular FormControl check if required
I needed something slightly more abstract, so I've adapted the answer from @siddajmera a bit to be able to use on any field.
In your .ts
file:
isRequiredField(field: string) {
const form_field = this.testForm.get(field);
if (!form_field.validator) {
return false;
}
const validator = form_field.validator({} as AbstractControl);
return (validator && validator.required);
}
Then, in your template file:
<div>
<label>Some Field:<span *ngIf="isRequiredField('some_field')">*</span></label>
<input [formControl]="form.controls['some_field']">
</div>
<div>
<label>Some Field:<span *ngIf="isRequiredField('another_field')">*</span></label>
<input [formControl]="form.controls['another_field']">
</div>
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.