Angular control.error is null on page load despite ng-required property set to true

I have a textbox component with attributes ng-minlength and ng-required set from variables required and minlength which are set to true and 3 respectively

    <div *ngIf="required" class="inline required">
      *
    </div>
    <div class="input-container inline">
      <input type="text"
             #txtBox="ngModel"
             [(ngModel)]="value"
             (focus)="onFocus($event)"
             (ngModelChange)="change($event)"
             ng-minlength="minlength"
             ng-required="required">
    
      <div *ngIf="txtBox.errors">
        <div class="row alert alert-danger alert-div">
          <div *ngIf="txtBox.errors?.['required']">
            <span>
              Required field
            </span>
          </div>
          <div *ngIf="txtBox.errors?.['minlength']">
            <span>
              Min length error
            </span>
          </div>
        </div>
      </div>
    </div>

I want to show the user the validation when this textbox is on focus or component loaded. However, the problem is txtBox.errors is null on component load. How to achieve this?

>Solution :

You are applying the validators incorrectly. The validators are called "minlength" and "required", without the "ng-"-prefix. Also if you assign variables to them, you need to use the syntax in [], otherwise Angular will interpret the value just as string.

So it should be:

      <input type="text"
             #txtBox="ngModel"
             [(ngModel)]="value"
             (focus)="onFocus($event)"
             (ngModelChange)="change($event)"
             [minlength]="minlength"
             [required]="required">

Leave a Reply