angulartypescriptangular12

No directive found with exportAs 'ngModel'. Angular 12


I am creating form validation in angular and I am getting error

No directive found with exportAs 'ngModel'.

My code:

<form>
  <div class="form-group">
      <label for="firstname">First Name</label>
      <input type="text" id="name" name="name" required minlength="4" 
                     appForbiddenName="bob" ngModel #name="ngModel">
                     
      <div class="alert alert-danger" *ngIf>First name required</div>
  </div>
  <div class="form-group">
      <label for="comment">Comment</label>
      <textarea name="" id="comment" cols="30" rows="10" class="form-control"></textarea>
  </div>
  <button class="btn btn-primary">Submit</button>
</form>

image of editor

The error:

     Error: src/app/app.component.html:6:60 - error NG8003: No directive found with exportAs 'ngModel'.
    
    6                      appForbiddenName="bob" ngModel #name="ngModel">
                                                                 ~~~~~~~
    
      src/app/app.component.ts:5:16
        5   templateUrl: './app.component.html',
                         ~~~~~~~~~~~~~~~~~~~~~~

Error occurs in the template of component AppComponent.


Solution

  • If you work with angular template-driven forms and want to use #name="ngModel" you also need to use [(ngModel)]="mymodel" directive in the same input, and of course,

    Add import { FormsModule } from '@angular/forms';
    

    to your app.module.ts and in the import array you need to add FormsModule.