【发布时间】: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