问题
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 or ngModelOptions
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 property required
) 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" />
回答1:
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
回答2:
I encounter this problem with a dynamic form. I must add new row into my form (which include inputs) and when I add new data to my form old fields values was clean.
I fix this with:
..*ngFor="let item in formArr; let i = index"...
..name="myInput-{{i}}" #myInput{{i}}="ngModel"..
来源:https://stackoverflow.com/questions/56108719/why-do-i-need-to-mention-name-attribute-or-ngmodeloptions-standalone-true-w