Angular: assign ngModel directive to template reference variable is not working

Viewed 180

I'm trying to use the template-driven form in angular, to validate the form. but due to some reason i'm not able to do.. please help me...

In the contact-form.comoponent.html, I'm using the template reference variable firstName and assign the ngModel to it like #firstName="ngModle". but this not working please a look at the following code.

contact-form.component.html

<div class="container">
    <form>
        <div class="form-group">
            <label for="firstName">First Name</label>
            <input ngModel
                   required
                   name="firstName" 
                   #firstName="ngModel"
                   type="text" 
                   id="firstName" 
                   class="form-control" 
                   (change)="log(firstName)"
                   >
            <div class="alert alert-danger" *ngIf="!firstName.valid"> First Name is required</div>
        </div>
        <div class="form-group">
            <label for="comment">Comment</label>
            <textarea id="comment" class="form-control"></textarea>
        </div>
        <button class="btn btn-primary">
            Submit
        </button>
    </form> 
</div>

contact-form.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'contact-form',
  templateUrl: './contact-form.component.html',
  styleUrls: ['./contact-form.component.css']
})
export class ContactFormComponent  {

  log(value: any) {
    console.log(value);
}

}

The Error is:

Initial Chunk Files | Names |     Size
main.js             | main  | 17.24 kB

4 unchanged chunks

Build at: 2021-07-08T11:36:58.617Z - Hash: b901bad1bbed00b7beb0 - Time: 822ms

Error: src/app/contact-form/contact-form.component.html:8:32 - error NG8003: No directive found with exportAs 'ngModel'.

8                    #firstName="ngModel"
                                 ~~~~~~~

  src/app/contact-form/contact-form.component.ts:5:16
    5   templateUrl: './contact-form.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component ContactFormComponent.
0 Answers
Related