【问题标题】:angular select reactive form dropdown problem角度选择反应形式下拉问题
【发布时间】:2021-10-31 00:43:20
【问题描述】:

我在 Angular 中选择下拉菜单时遇到问题。我使用反应形式,但下拉菜单不起作用,我不知道为什么以及如何修复它。有人可以帮帮我吗?谢谢。

TS 代码

form: FormGroup = new FormGroup({});
genderList = [{ type: 'Female' }, { type: 'Male' }];

selectedObject: any = this.genderList[0];

consoleLog(state: any) {
    console.log(state);
  }

HTML

<select
        [formControlName]="selectedObject"
        class="form-control"
        (change)="consoleLog(selectedObject)"
        [(ngModel)]="selectedObject"
      >
        <option *ngFor="let g of genderList" [ngValue]="g">
          {{ g.type }}
        </option>
      </select>

在 UI 中,代码在下拉菜单中无法正常工作,我明白了:

core.js:6479 ERROR Error: 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).

      Example:

      
    <div [formGroup]="myGroup">
      <input formControlName="firstName">
    </div>

知道如何解决它以便能够选择此人的性别吗?非常感谢您的宝贵时间。

问候

【问题讨论】:

  • 错误很明显。您是否在 div 或表单中设置了 formGroup 值的选择控件?当您使用 Reactive Forms 时,为什么要使用 ngModel?那是行不通的。
  • 您好,R. Richards,感谢您的回复。是的,我有一个像这样的表单
    并且我读到 ngModel 它不起作用但我无法使其工作,我不知道如何绑定表单 ControlName 以便使代码工作。你有什么建议或想法吗?非常感谢
  • 你应该阅读这个:angular.io/guide/reactive-forms

标签: javascript angular forms


【解决方案1】:

正如理查兹所说,你不能同时使用反应式和模板驱动(ngModel)方法,从你的问题的标题来看,我猜你想使用反应式方法,所以删除 ngModel 并修复 formControlName,它接受字符串,但你将它与一个对象绑定,它应该是这样的:

<form [formGroup]="myGroup">
    <select formControlName="gender"> other stuff... </select>
</form>

其中性别只是一个普通字符串而不是属性,或者您也可以这样做:

<select [formControlName]="'gender'">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-21
    • 2016-11-13
    • 1970-01-01
    • 2020-05-19
    • 2023-02-03
    • 1970-01-01
    • 2016-03-01
    • 1970-01-01
    相关资源
    最近更新 更多