Angular : If ngModel is used within a form tag, either the name attribute must be set
Dung Do Tien Jun 19 2021 317
In a small Angular project. I have a login form as below:
<div class="app-body">
<main class="main d-flex align-items-center">
<div class="container">
<div class="row">
<div class="col-md-8 mx-auto">
<div class="card-group">
<div class="card p-4">
<div class="card-body">
<form>
<h1>Login</h1>
<p class="text-muted">Sign In to your account</p>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="icon-user"></i></span>
</div>
<input type="text" class="form-control" placeholder="Username" [(ngModel)]="username" autocomplete="username" required>
</div>
<div class="input-group mb-4">
<div class="input-group-prepend">
<span class="input-group-text"><i class="icon-lock"></i></span>
</div>
<input type="password" class="form-control" placeholder="Password"[(ngModel)]="password" autocomplete="current-password" required>
</div>
<div class="row">
<div class="col-6">
<button type="button" (click)=dologin class="btn btn-primary px-4">Login</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</main>
</div>
When I run project I get an 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.
ERROR 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.
Example 1: <input [(ngModel)]="person.firstName" name="first">
Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">
How can I resolve it?
Have 2 answer(s) found.
- N0
Nguyễn TrươngAnh Tuấn Jun 19 2021
Another one thing. If used
ngModel
you need to addname
attribute.<input type="text" name="firstName" [(ngModel)]="firstName"/>
This is the common thing for using
ngModel
. - S-1
Suthep Sangvirotjanaphat Jun 19 2021
I think the error message is very clear, you can choose one way below to resolve your issue
<!--Add the 'name' attribute--> <input [(ngModel)]="username" name="username"> <!--Or [ngModelOptions]="{standalone: true}" --> <input [(ngModel)]="username" [ngModelOptions]="{standalone: true}">
I hope it works for you!
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.