【问题标题】:How to use formControlName in a child component and then get value of it in the parent?如何在子组件中使用 formControlName 然后在父组件中获取它的值?
【发布时间】: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).

我明白这意味着什么,但不知道在这种情况下如何处理它..

【问题讨论】:

  • 为什么不将&lt;add-picklist&gt; 设为自定义表单控件?有很多关于这个的信息
  • 你的意思是实现ControlValueAccessor

标签: javascript html angular angular-reactive-forms reactive-forms


【解决方案1】:

您不能使用自定义 @Input formControlName,因为 Angular 也尝试使用它。
如果你重命名它会起作用(formGroup 也一样)

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

那么,您不能使用[formControlName],因为父表单不在同一个 HTML 代码中(它在父表单中)。
相反,请使用[formControl]="formGroupParent[formControlNameParent]"

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

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

【讨论】:

  • 这很奇怪,现在我有 Cannot find control with unspecified name attribute 错误,即使我尝试在输入中添加名称或 formControlName 属性
  • @D.Zet 是的,输入必须有名称。请看我的编辑(包括*ngIf安全)
  • 是的,我知道,但即使设置了[name],也会出现错误提示:Cannot find control with unspecified name attribute 所以这真的很奇怪
  • @D.Zet 是的,但是您是否按照我的建议添加了*ngIf?如果是,您可以制作一个堆栈闪电战来重现您的问题吗?肯定有其他问题。
猜你喜欢
  • 2018-03-18
  • 2017-04-01
  • 2017-04-07
  • 1970-01-01
  • 2019-11-30
  • 1970-01-01
  • 2019-08-31
  • 2018-02-26
  • 1970-01-01
相关资源
最近更新 更多