Unable to validate requiredLength in Angular 2

65 views
Skip to first unread message

Dawg

unread,
Sep 27, 2016, 9:01:04 AM9/27/16
to AngularJS
Hello,
 I'm trying to figure out how to validate the requiredLength but it keeps crashing on this point. I highlighted the line in red where it seems to be crashing.
Any ideas as to what I'm doing wrong?

This is my input field:

                        <input type="text" 
                              class="form-control" 
                                 id="userName"  
                        placeholder="userName"
                    formControlName="userName">
                   </div>              
                    <div *ngIf="myForm.controls.userName.touched && myForm.controls.userName?.errors?.required" >req. field</div>
                    <div *ngIf="myForm.controls.userName.errors.minlength.requiredLength"> required length 3 test </div>

Angular 2 script:
ngOnInit(){  
this.myForm = this._fb.group({
userName: ['', [Validators.required, Validators.minLength(3)]], 
password: ['pwd',Validators.required]
})
}

onSubmitLogin(x){
console.log(x);
}


Error message received:
core.umd.js:3462 EXCEPTION: Error in app/views/user-login.component.html:23:25 caused by: Cannot read property 'requiredLength' of undefined



Sander Elias

unread,
Sep 29, 2016, 2:49:00 PM9/29/16
to AngularJS
Hi Dawg,

You need the elvis operator.

<div *ngIf="myForm.controls.userName?.errors?.minlength?.requiredLength">

The difference with NG1 is that in NG2 it is not allowed to have non existing properties in your template.

Regards
Sander
Reply all
Reply to author
Forward
0 new messages