【发布时间】:2020-12-23 19:11:24
【问题描述】:
所以基本上我创建了我自己的组件,该组件是可过滤选择的,带有将新项目添加到pickListItems 的选项。问题是我想将输入值作为 formControl,但即使我将 formGroup 传递给孩子,我也会遇到错误。
所以示例代码如下所示:
<form [formGroup]="formGroup">
some stuff here to generate form fields, one of fields is my component with
select:
<app-add-picklist
[field]="field"
[formControlName]="field.Label"
[formGroup]="formGroup">
</app-add-picklist>
<form>
在add-picklist 组件中我有:
@Input() formGroup: FormGroup;
@Input() formControlName: string;
@Input() field: any;
在 ngOnInit 中:
ngOnInit() {
this.formGroup.addControl(this.formControlName, new FormControl());
}
还有模板(部分):
<input type="text"
class="form-control"
placeholder="Pick one"
aria-label="Number"
matInput
[formControlName]="formControlName"
[matAutocomplete]="auto">
所以我不断收到错误
No value accessor for form control with name: xxxx.
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).
我明白这意味着什么,但不知道在这种情况下如何处理它..
【问题讨论】:
-
为什么不将
<add-picklist>设为自定义表单控件?有很多关于这个的信息 -
你的意思是实现
ControlValueAccessor?
标签: javascript html angular angular-reactive-forms reactive-forms