Angular2 If ngModel is used within a form tag, either the name attribute must be set or the form

I am getting this error from Angular 2

core.umd.js:5995 EXCEPTION: Uncaught (in promise): Error: Error in app/model_exposure_currencies/model_exposure_currencies.component.html:57:18 caused by: 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.

Example 1:

<input [(ngModel)]="person.firstName" name="first">

Example 2:

<input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}"> 
<td *ngFor="let lag of ce.lags">
    <div class="form-group1">
        <input name="name" [(ngModel)]="lag.name" [ngModelOptions]="{standalone: true}"  class="form-control" pattern="[0-9]*(\.[0-9]+)?" required>
    </div>
</td>

This is how I use form tag:

<form #f="ngForm" (ngSubmit)="onSubmit()">

If ngForm is used, all the input fields which have [(ngModel)]="" must have an attribute name with a value.

<input [(ngModel)]="firstname" name="something">

Standalone

By setting [ngModelOptions]="{standalone: true}" one tells Angular something like, ignore the form and/or ngForm, just bind it to firstname variable please.

However, if form-tag was used by mistake (like in my case sometimes), changing form to div is another option (but only if your styles don't need form-tag).


As every developer have a common habit, not to read the complete error, just read the first line and start looking for answer from someone else :):) I am also one of them, that's why I am here:

Read the error, clearly saying:

Example 1: <input [(ngModel)]="person.firstName" name="first">
Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">

What more we need to understand this error?

Use any one option everything will work smooth.


In my case the error happened because below in html markup one more line existed without the name attribute.

<form id="form1" name="form1" #form="ngForm">
    <div class="form-group">
        <input id="input1" name="input1" [(ngModel)]="metaScript" />
        ... 
        <input id="input2" [(ngModel)]="metaScriptMessage"/>
    </div>
</form>

But the browser still reports the first row has the error. And it's difficult to discover the source of mistake if you have other elements between these two. screenshot of chrome devtools showing the error


Both attributes are needed and also recheck all the form elements has "name" attribute. if you are using form submit concept, other wise just use div tag instead of form element.

<input [(ngModel)]="firstname" name="something">

I noticed that the Chrome developer tool sometimes only underlines the first element in swiggly red even if it is correctly set up with a name. This threw me off for a while.

One must be sure to add a name to every element on the form that contains ngModel regardless of which one is squiggly underlined.