本文介绍了为什么我需要提及 name 属性或 ngModelOptions="{standalone: true}";在使用 ngModel 时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究 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.

ERROR 错误:如果在表单标签中使用 ngModel,要么必须设置 name 属性,要么必须将表单控件定义为ngModelOptions 中的独立".

示例 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}" 应用到我的所有字段时,那么我的表单在所有情况下的 valid = 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" />

推荐答案

表单只是一组键/值对.Name 是用于标识/获取/设置该控件值的键,因此您需要指定每个控件的名称.当您设置 ngModelOptions="{standalone: true}" 时,您告诉 angular 不要将此输入包含到表单中.这就是为什么您的表格始终有效.它实际上是空的.

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 时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 12:11