I\'m using Material 2 in my app, but in this question I want to solve a problem specifically with Input.
As you can see in API Reference there\'s a
There is no straight forward or clean way of doing this. Here is the cleanest method that I came across that works. Tested with the latest version of Angular v10.2.0 (as of today)
Import these
import {AbstractControl, FormControl, Validators} from '@angular/forms';
Define your control
anyCtrl = new FormControl('', [Validators.required]);
Add this method
public hasRequiredField = (abstractControl: AbstractControl): boolean => {
if (abstractControl.validator) {
const validator = abstractControl.validator({}as AbstractControl);
if (validator && validator.required) {
return true;
}
}
return false;
}
How to call this method from the HTML
Calling it from the Typescript file (logic) within the constructor or ngOnInit
constructor() {
console.log(this.hasRequiredField(this.anyCtrl)); // true, false if Validators array does not contain Validators.required
}