Deadpool
Deadpool

Reputation: 8240

Simple Template-Driven Form Angular4 is giving error

Making a simple 'Template-Driven Form' I am getting error though I've not done anything special. This is a simple form with one input with one required validation. That's all. Can someone help me out?

abc.component.html

<form #customForm="ngForm" (ngSubmit)="alpha(customForm)">

  <input type="text" name="firstName" ngModel #firstName="ngModel" required><br/>

  <div class="red" *ngIf="customForm.firstName.touched">
    <div *ngIf="customForm.firstName.errors.required">Input field is required!</div>
  </div>

  <button type="submit" [disabled]="customForm.invalid">Submit</button>

</form>

Error:

Cannot read property 'touched' of undefined

Snapshot:

enter image description here

Can someone point out, what exactly am I doing wrong?

Upvotes: 1

Views: 804

Answers (2)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24424

You don't need to use customForm you got the refrence to direcly by #firstName

  <div class="red" *ngIf="firstName.touched">
    <div *ngIf="firstName.errors.required">
      Input field is required!
    </div>
  </div>

but still firstName.errors.required will throw an error when the form controll is valid you can use ?. operator or you need to update ngIf expresstion like this

<div class="red" *ngIf="firstName.touched && firstName.invalid">

or you can use '?.' operator

  <div *ngIf="firstName.errors?.required">Input field is required!</div>

When the form Control is valid the errors property will be null

stackblitz demo

Upvotes: 1

SiddAjmera
SiddAjmera

Reputation: 39442

Since you're already declaring a template and assigning it the value of ngModel by doing #firstName="ngModel", the firstName template variable will already have the firstName FormControl. So you can simply apply a check on that like this: *ngIf="firstName.touched"

Change your template like so:

<form 
  #customForm="ngForm" 
  (ngSubmit)="alpha(customForm)">
  <input 
    type="text" 
    name="firstName" 
    ngModel 
    #firstName="ngModel" 
    required>
  <br/>
  <div 
    class="red" 
    *ngIf="firstName.touched">
    <div 
      *ngIf="firstName.errors.required">
      Input field is required!
    </div>
  </div>
  <button 
    type="submit" 
    [disabled]="customForm.invalid">
    Submit
  </button>
</form>

Here's a Working StackBlitz for your ref.

Upvotes: 2

Related Questions