If ngModel is used within a form tag, either the name attribute must be set or the form control must

原文链接:这里
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>

这样表单就好看多了。

If ngModel is used within a form tag, either the name attribute must be set or the form control must

 

上一篇:Jenkins(5)生成allure报告


下一篇:springboot实战小项目-前端-主体部分