Check if input control has a specific vallidator type in angular2

I have a component that wraps an input field. In the component, I get the object Controlfrom @Input() inputControl: Control;. In the template, I have a range that displays a message if the input field in the component is not required.

<span
  class="input-label-caption">
  (optional)
</span>

and the entrance

<input
    *ngIf="inputMode=='text' || inputMode=='email'"
    type="{{inputMode}}"
    [ngFormControl]="inputControl"
    placeholder="{{placeholder}}"
    class="input-text"
    [disabled]="inputDisabled"
    [ngClass]="{
    'inverted': inverted
    }">

How can I read a form object inputControlif it contains Validators.required? I want to know if I can use it like this

<span
  class="input-label-caption"
  *ngIf="!inputControl.validators.required"
  >
  (optional)
</span>
+4
source share
2 answers

You can try using this expression:

<span
  class="input-label-caption"
  *ngIf="!inputControl.errors?.required"
>
  (optional)
</span>

The attribute errorscontains one entry for the name of the failed validator.

Elvis errors, undefined, .

Edit

, , "" , === Validators.required. - , Validators.required "" .

:

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

, validator , , , Validators.required.

:

()

, , Thierry

+5

, , Angular . Angular (2.2.0) - .

  get required(): boolean { 
    var _validator: any = this.inputControl.validator && this.inputControl.validator(this.inputControl);
    return _validator && _validator.required;
  }

, , .

      name: ['', [Validators.required, Validators.minLength(2)]]
+3

Source: https://habr.com/ru/post/1624822/


All Articles