Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading