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.

原文链接:这里
0.背景

angular项目,用的NG-ZORRO

一个简单的表单提交页面,本来不想用form,直接写的row和col。但是页面太丑了,加上form吧,开始报错(其实就是不熟练)。

1.报错原因及解决方法

我的当时的非主流代码如下:

<form nz-form>
<nz-row>
<nz-col nzSpan="12">
<nz-form-item>
<nz-form-label [nzSm]="6" [nzXs]="24" nzFor="region">地区</nz-form-label>
<nz-form-control [nzSm]="18" [nzXs]="24">
<input nz-input [(ngModel)]="tableData.region" formControlName="region"
placeholder="地区" id="region"/>
</nz-form-control>
</nz-form-item>
</nz-col>
<nz-col nzSpan="12">
<nz-form-item>
<nz-form-label [nzSm]="6" [nzXs]="24" nzFor="lawCode">项目名称</nz-form-label>
<nz-form-control [nzSm]="18" [nzXs]="24">
<input nz-input [(ngModel)]="tableData.lawCode" formControlName="lawCode"
placeholder="项目名称" id="lawCode"/>
</nz-form-control>
</nz-form-item>
</nz-col>
</nz-row>
</form>

一开始直接用的input,后来觉得不好看,改成form后,开始报下面的错:

formControlName must be used with a parent formGroup directive. You'll want to add a formGroup
directive and pass it an existing FormGroup instance (you can create one in your class).

我想了想我这个非主流代码,于是就把formControlName给删除了,结果报错:

If ngModel is used within a form tag, either the name attribute must be set or the form<br>control must be defined as 'standalone' in ngModelOptions.

大概的意思是,如果你要在form中使用ngModel,必须定义stanalone。好吧,终于根据提示加上了代码。

<form nz-form>
<nz-row>
<nz-col nzSpan="12">
<nz-form-item>
<nz-form-label [nzSm]="6" [nzXs]="24" nzFor="region">地区</nz-form-label>
<nz-form-control [nzSm]="18" [nzXs]="24">
<input nz-input [(ngModel)]="tableData.region" [ngModelOptions]="{standalone: true}"
placeholder="地区" id="region"/>
</nz-form-control>
</nz-form-item>
</nz-col>
<nz-col nzSpan="12">
<nz-form-item>
<nz-form-label [nzSm]="6" [nzXs]="24" nzFor="lawCode">项目名称</nz-form-label>
<nz-form-control [nzSm]="18" [nzXs]="24">
<input nz-input [(ngModel)]="tableData.lawCode" [ngModelOptions]="{standalone: true}"
placeholder="项目名称" id="lawCode"/>
</nz-form-control>
</nz-form-item>
</nz-col>
</nz-row>
</form>

这样表单就好看多了。

 

posted on   longkui  阅读(156)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示