0

I am new to Angular. Trying to use the ng-model directive for 2 way binding

I have tried 2 ways to do it

<!-- <input type="email" class="form-control" id="email" placeholder="EMAIL" ngModel name ="email"> -->
     <input type="email" class="form-control" id="email" placeholder="EMAIL" [(ngModel)]="email">

Both of them are described above

First one is working where and second is not

Could you please explain me the problem in the second line which is not working using [(ngModel)].

Is this an incorrect syntax?

Forms module is already imported in app.module.ts

2
  • Insufficient context and vague description of problem as "not working" Commented Jan 15, 2021 at 7:05
  • Please make sure that you have following import in your module: import { FormsModule } from '@angular/forms'; Commented Jan 15, 2021 at 7:07

3 Answers 3

1

Add the name attribute in the input field to bind form with name

or

use [ngModelOptions]="{standalone: true}"

<input type="email" class="form-control" name="email" id="email" placeholder="EMAIL" [(ngModel)]="email">

<input type="email" class="form-control" [ngModelOptions]="{standalone: true}" id="email" placeholder="EMAIL" [(ngModel)]="email">

` id="email" placeholder="EMAIL" [(ngModel)]="email">

Sign up to request clarification or add additional context in comments.

Comments

0

You need to have the following import in your module:

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

For more details, you can refer to official documentation here:

https://angular.io/guide/built-in-directives#ngmodel-two-way-binding

Edit: This is a very basic example, using your input element as-is:

https://stackblitz.com/edit/angular-anjdwq?embed=1&file=src/app/app.component.ts

3 Comments

I did that in both component class file and also in ap.module.ts file. But it is giving error : 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.
Please check this example that I added to my answer as well: stackblitz.com/edit/angular-anjdwq?embed=1&file=src/app/…
Hi Umair, This example seems to have an error . Input does not seem to be displayed. Could you please fix it. At present preview seems to be blank
0

I guess you are using ngForm. In that case, all the input fields which have [(ngModel)]="" must have an attribute name with a value.

<input type="email" class="form-control" id="email" placeholder="EMAIL" [(ngModel)]="email" name="email">

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.