Angular5 Error: ngModel cannot be used to register form controls with a parent formGroup directive

An error occurred while creating a form:

The reason is that the formgroup instruction is used in the outermost form, but the ngmodel instruction is used in one of the following input elements, but the formcontrol instruction or formcontrolname attribute is not added

In other words, if formgroup is used in the form, all input elements contained in the form need to define a formcontrol. If not, an error will be reported

 1   <form [formGroup]="form">
 2     <mat-form-field>
 3       <input matInput placeholder="IP(SNMP)" [formControl]="snmpIpCtrl" required>
 4       <mat-error *ngIf="snmpIpCtrl.hasError('required')">IP(SNMP)不能为空</mat-error>
 5       <mat-error *ngIf="snmpIpCtrl.hasError('pattern')">请输入有效的IP地址</mat-error>
 6     </mat-form-field>
 7     
 8     <div>
 9       <p>是否支持Netconf</p>
10       <mat-radio-group [(ngModel)]="netconfFlag">
11         <mat-radio-button value="0" color="primary">支持</mat-radio-button>
12         <mat-radio-button value="1" color="primary">不支持</mat-radio-button>
13       </mat-radio-group>
14     </div>
15 </form>

Solution 1:

Add the formcontrol directive or formcontrolname attribute to the input element

1 <div>
2       <p>Whether Netconf is supported or not</p>
3       <mat-radio-group [(ngModel)]="netconfFlag" [formControl]="netconfFlagCtrl">
4         <mat-radio-button value="0" color="primary">supported</mat-radio-button>
5         <mat-radio-button value="1" color="primary">NOT supported</mat-radio-button>
6       </mat-radio-group>
7 </div>

The formcontrol for verification is defined in the corresponding component.ts

Solution 2:

Instead of adding formcontrol directive or formcontrolname attribute, add ngmodeloptions directive

Note that ngmodel options must be used with ngmodel

1     <div>
2       <p>Whether Netconf is supported or not</p>
3       <mat-radio-group [(ngModel)]="netconfFlag" [ngModelOptions]="{standalone: true}">
4         <mat-radio-button value="0" color="primary">supported</mat-radio-button>
5         <mat-radio-button value="1" color="primary">NOT supported</mat-radio-button>
6       </mat-radio-group>
7     </div>

Similar Posts: