Kliment Kliment - 1 year ago 62
TypeScript Question

Check if input control has certain type of vallidator in angular2

I have component that wraps input field. In the component i receive the

object from
@Input() inputControl: Control;
. In the template i have span that shows message if input field in the component is not required.


and the input

*ngIf="inputMode=='text' || inputMode=='email'"
'inverted': inverted

How can i read form
object if it contains
I want to know if i can used it like this for example


Answer Source

You can try to use this expression:


The errors attribute contains one entry per name of validator that failed.

I use the Elvis operators for the errors attribute since it can be undefined if there is no validation error.


Following your comment, I think that you can check a "required" validator using the === operator with the Validators.required function directly. In fact a validator is simply a function and the Validators.required function is used for "required" validation.

Here is the corresponding code:

this.hasRequiredValidator = (this.inputControl.validator === Validators.required);

In the case where the validator attribute is an array, you need to extend a bit the test to check if the Validators.required function is present in the array.

Now the code in the template would be:


Hope it helps you, Thierry

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download