Search code examples
angularionic3angular4-forms

Angular 4 Forms Validation - browser crashes when exporting ngModel


I have a simple input control I want to validate using Angular Forms validation, e.g.

<form>
<ion-input type="tel" id="phoneNumber" name="phoneNumber" required [(ngModel)]="phoneNumber" maxlength="10" minlength="10"
  placeholder="Touch here to enter a phone number" class="form-control">
</ion-input>
<p *ngIf="!phoneNumber.pristine && phoneNumber.errors.required" style="color:red;">
  * Phone number is required.
</p>
<button ion-button block large full (ngSubmit)="placeOrder()">Place order</button>
</form>

I'm trying to follow along with Angular's documentation for template-driven forms: https://angular.io/guide/forms

Problem I'm having is that as soon as the browser hits the page, the browser just hangs, and only way out is to end the browser process. A CPU core will spike and the memory will keep increasing to more than 1GB within a minute. This is an Ionic 3 application with Angular 4. I've added the FormsModule to my app.module.ts file.

Any ideas why this would be happening?

I've found that when I remove either of the conditions inside my *ngIf, the issue does not occur (although obviously there is no validation then).


Solution

  • Your input is bound, using ngModel to the property phoneNumber of your component. So, whatever you enter in that input becomes the value of phoneNumber. What you input is a string. So phoneNumber is a string.

    Strings don't have a pristine or an errors property. So phoneNumber.pristine makes no sense. Those are properties of the FormControl object created by the ngModel directive, which contains the state of the input. To access this FormControl object (through the ngModel directive), you need to expose the directive as a variable in your template:

    <ion-input type="tel" id="phoneNumber" name="phoneNumber" required 
               [(ngModel)]="phoneNumber" #phoneNumberControl="ngModel" 
               maxlength="10" minlength="10"
               placeholder="Touch here to enter a phone number" class="form-control">
    </ion-input>
    <p *ngIf="!phoneNumberControl.pristine && phoneNumberControl.errors.required" style="color:red;">
      * Phone number is required.
    </p>