Skip to main content
 首页 » 编程设计

angular中如何修复 ngModel 无法用于使用父 formGroup 指令注册表单控件

2025年05月04日297qq78292959

我的 Angular 项目中有这一行:

 <option *ngFor="let item of painLevels" value="{{item.id}}">{{item.painlevel}}</option> 

我收到此错误:

ngModel cannot be used to register form controls with a parent formGroup directive. Try using formGroup's partner directive "formControlName" instead.

如何将 [ngModelOptions]="{standalone: true}"应用于下拉菜单?我看到的只是输入的示例。或者有更好的方法来解决这个问题吗?

请您参考如下方法:

你可以像我下面的例子一样使用;

<select name="country" formControlName="country" id="country" class="form-control form-control-element" [(ngModel)]="country"> 
  <option value="90">Turkey</option> 
  <option value="1">USA</option> 
  <option value="30">Greece</option> 
</select> 

不要忘记使用formControlName="country"

并且不要忘记阅读 angular.io 的更新说明

Support for using the ngModel input property and ngModelChange event with reactive form directives has been deprecated in Angular v6 and will be removed in Angular v7.