如何在子组件中使用formControlName,然后在父组件中获取其值?

问题描述

因此,基本上我创建了自己的组件,该组件是可过滤的select,带有将新项添加到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).

我理解这是什么意思,但不知道在这种情况下如何处理。

解决方法

您无法使用自定义@Input formControlName,因为Angular也会尝试使用它。
如果重命名,它将起作用(与formGroup相同)

@Input() formGroupParent: FormGroup;
@Input() formControlNameParent: string;

然后,您不能使用[formControlName],因为父表单不在同一HTML代码中(位于父表单中)。
而是使用[formControl]="formGroupParent[formControlNameParent]"

此外,输入必须具有名称。必须添加它,并添加一个*ngIf,因为名称是@Input(),并且在某些毫秒内将为null(在构造函数和ngOnInit被触发之间的时间)...

<input *ngIf="formGroupParent && formControlNameParent" 
   type="text"
   [name]="formControlNameParent"
   class="form-control"
   placeholder="Pick one"
   aria-label="Number"
   matInput
   [formControl]="formGroupParent[formControlNameParent]"
   [matAutocomplete]="auto">