问题描述
我正在制作一个Angular Form.我有一个具有某些属性的域模型.我通过使用 ngModel
绑定它们.
I am working on an Angular Form. I have a domain model with some properties. I am binding them by using ngModel
.
在此期间,如果我不使用 name
属性,则会收到以下错误消息.
During this, if I don't use name
attribute then I get the below error.
示例1:
<input [(ngModel)]="person.firstName" name="first">
示例2:
<input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">
为什么在双向绑定中绑定域模型时,为什么需要提及 name
属性或 ngModelOptions
?
Why do I need to mention name
attribute or ngModelOptions
while I am binding domain model in two-way binding?
当我将 ngModelOptions ="{standalone:true}"
应用于我的所有字段时,那么无论是否需要控件(具有属性的控件,
)是否有价值.
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.
我的表单是:
<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" />
推荐答案
表单只是一组键/值对.名称是用于标识/获取/设置此控件的值的键,因此您需要指定每个控件的名称.当您设置 ngModelOptions ="{standalone:true}"
时,您会告诉不要将该输入包括在表单中.这就是为什么您的表格始终有效.它实际上是空的.
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
这篇关于为什么我需要提及name属性或ngModelOptions =“" {standalone:true}“在使用ngModel时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!