菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
433
0

Angular学习笔记 ——input 标签上的【name属性】和【ngModelOptions属性】

原创
05/13 14:22
阅读数 20453

利用“@angular/forms" 创建<form>表单的时候,系统默认会创建一个”FormGroup"的对象。

使用带有“ngModel"的”<input>“标签时,系统会自动为这个标签创建一个叫做”FormControl"的对象,并且会自动把它添加到”FormGroup"中。而“FormControl"在”FomGroup“中是用"<input>"标签上的”name"属性来做标识的。

例如下面这个例子:

<form #f="ngForm">
    <input type="text" [(ngModel)]="firstFieldVariable" name="firstField">
    <span>{{ f.controls['firstField']?.value }}</span>
</form>

如果没有使用“name”这个属性,那系统就会报错:

<form #f="ngForm">
<input type="text" [(ngModel)]="firstFieldVariable"> </form>
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.

解决方法除了把“name”属性添加上外,还有第二种选择,就是给"<input>"标签设置一个

ngModelOptions

属性:

[ngModelOptions]="{standalone: true}"

当设置了这个属性,<input>的 FormControl 对象就不会添加到FormGroup内,也就不能通过

{{ f.controls['firstField']?.value }} 索引到该对象的值了。

参考: https://github.com/angular/angular/issues/9230#issuecomment-228116474

发表评论

0/200
433 点赞
0 评论
收藏