Why do I need to mention name attribute or ngModelOptions="{standalone: true}" while using ngModel?
Form is just a set of key/value pairs. Name is the key which is used to identify/get/set the value of this control, so you need to specify the name of each control. When you set ngModelOptions="{standalone: true}"
you tell angular to not include this input into the form. That's why your form is always valid. It is actually empty.
https://angular.io/api/forms/NgModel#options
TAB
A Passionate Fullstack Software Engineer. Working since 2004.
Updated on June 16, 2022Comments
-
TAB almost 2 years
I am working on an Angular Form. I have a domain model with some properties. I am binding them by using
ngModel
.During this, if I don't use
name
attribute then I get the below error.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}">
Why do I need to mention
name
attribute orngModelOptions
while I am binding domain model in two-way binding?When I applied
ngModelOptions="{standalone: true}"
to all of my fields, then my form's valid = true in all cases whether the control (with propertyrequired
) has value or not.My form is:
<form #detailForm="ngForm" (ngSubmit)="save(detailForm)" id="ngForm"> </form>
While my submit button is outside the form:
<input type="button" form="ngForm" class='Button' value="Save" (click)="detailForm.ngSubmit.emit()" [disabled]="!detailForm.form.valid" />