Angular 2 [(ngModel)] 放在 <form></form> 之间时抛出错误
Angular 2 [(ngModel)] throws error when placed between <form></form>
我有一个 component.html 表单,其代码如下所示:
<div *ngIf="client">
//More divs
<form class="form-horizontal" (ngSubmit)="onSubmit()" #clientForm="ngForm">
<div>
<input class="form-control" #name="ngModel" [(ngModel)]="client.name" required>
</div>
//End of more divs
</form>
</div>
但是当组件渲染 html:
时,我一直收到错误消息
Uncaught (in promise): TypeError: undefined is not an object
只有在表单之间放置 输入标签 时才会发生这种情况。它应该在哪里。如果我将输入标签放在 表单标签 的上方和之前,它可以很好地呈现数据。为什么会这样?
这与放置无关,我假设您没有定义对象 client
,因为您绑定到 client.name
;
您必须初始化为默认值,如
client = {};
在您的组件或真实的客户端对象中
PS。我想建议您停止使用 NGModel go with FormGroup。在您开始使用它之后,您会爱上它们 :) 快速、简单和灵活
您缺少输入控件上的 name
属性。应该是
<input class="form-control" name="clientName" #name="ngModel" [(ngModel)]="client.name" required>
如果删除名称属性并打开控制台,您将看到如下错误消息:
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.
这是一个Plunker
我有一个 component.html 表单,其代码如下所示:
<div *ngIf="client">
//More divs
<form class="form-horizontal" (ngSubmit)="onSubmit()" #clientForm="ngForm">
<div>
<input class="form-control" #name="ngModel" [(ngModel)]="client.name" required>
</div>
//End of more divs
</form>
</div>
但是当组件渲染 html:
时,我一直收到错误消息Uncaught (in promise): TypeError: undefined is not an object
只有在表单之间放置 输入标签 时才会发生这种情况。它应该在哪里。如果我将输入标签放在 表单标签 的上方和之前,它可以很好地呈现数据。为什么会这样?
这与放置无关,我假设您没有定义对象 client
,因为您绑定到 client.name
;
您必须初始化为默认值,如
client = {};
在您的组件或真实的客户端对象中
PS。我想建议您停止使用 NGModel go with FormGroup。在您开始使用它之后,您会爱上它们 :) 快速、简单和灵活
您缺少输入控件上的 name
属性。应该是
<input class="form-control" name="clientName" #name="ngModel" [(ngModel)]="client.name" required>
如果删除名称属性并打开控制台,您将看到如下错误消息:
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.
这是一个Plunker