Search code examples
angularangular-ngmodelangular2-formsangular2-ngmodel

Angular 2 [(ngModel)] throws error when placed between <form></form>


I have a component.html with a form with a code that looks like this:

<div *ngIf="client">
    //More divs
   <form class="form-horizontal" (ngSubmit)="onSubmit()" #clientForm="ngForm">
      <div>
         <input class="form-control" #name="ngModel" [(ngModel)]="client.name" required>
      </div>
    //End of more divs
   </form>
</div>

But I keep getting an error when the componente is rendering the html:

Uncaught (in promise): TypeError: undefined is not an object

It only happens if I place the input tag between the form. Where it should be. If I place the input tag above and prior to the form tag it renders just fine with the data. Why could this be happening?


Solution

  • You're missing your name attribute on the input control. Should be

    <input class="form-control" name="clientName" #name="ngModel" [(ngModel)]="client.name" required>
    

    If you delete the name attribute and open up the console you'll see the error message as follows:

    If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions.

    Here's a Plunker