Search code examples
javascriptangularformsangular-ngmodel

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?


Solution

  • 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.