Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with angular 2 ngControl's minlength errors validator

I have the following angular 2 form:

<form (ngSubmit)="updateFirstName()" #firstNameForm="ngForm" novalidate>
    <div class="form-group" ng-class="getCssClasses(formCtrl, formCtrl.firstName)">
        <div class="input-group">
            <input type="text"
                   ngControl="firstName"
                   #firstName="ngForm"
                   required
                   minlength="2"
                   maxlength="35"
                   pattern_="FIRST_NAME_PATTERN"
                   [ngModel]="currentUserAccount?.firstName"
                   (ngModelChange)="currentUserAccount ? currentUserAccount.firstName = $event : null"
                   placeholder="{{'FIRST_NAME_FORM.NEW_FIRST_NAME'| translate }}"
                   class="form-control"/>
        </div>

        <div [hidden]="firstName.valid">
            <div *ngIf="firstName.errors.minlength" class="control-label">{{'FIRST_NAME_FORM.MIN_LENGTH'| translate}}</div>
        </div>
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary pull-right" [disabled]="buttonDisabled">{{'FIRST_NAME_FORM.SUBMIT'| translate}}</button>
        <a [routerLink]="['/dashboard/useraccount']" class="btn btn-link pull-right text-right">{{'FORM_CANCEL' | translate}}</a>
    </div>
</form>

However it seems errors is null as I get the following error when I load the form in the browser:

TypeError: Cannot read property 'minlength' of null

What I am getting wrong here?

Is the declarative use of minlength attribute in the template not sufficient?

Is there another way to declare the minlength validator than in a programmatic way i.e.

this.name = new Control('', Validators.minLength(4));

?

like image 279
balteo Avatar asked May 15 '16 13:05

balteo


1 Answers

I have faced the same problem, i.e. TypeError: Cannot read property 'minlength' of null. For me, the solution proposed by @yurzui solved the problem. I am adding it as an answer here (as suggested by @günter-zöchbauer), so that others (who may not read the comments) can easily find it.

Problem:

The minlength property may be accessed, before errors is defined:

<div *ngIf="firstName.errors.minlength">
    Too short
</div>

Solution:

Use the ? operator to ensure that errors is defined, before accessing its minglength property:

<div *ngIf="firstName.errors?.minlength">
    Too short
</div> 

Alternative Solution:

Wrap your div in another div that checks if errors is defined:

<div *ngIf="firstName.errors">
    <div *ngIf="firstName.errors.minlength">
        Too short
    </div> 
</div>

Note that both solutions assume that firstName is defined.

PS: For anyone who needs it, the same applies to errors.maxlength as well!

like image 105
Ben Avatar answered Sep 20 '22 17:09

Ben