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>
这样表单就好看多了。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?