将自定义组件添加到反应式表单的 FormGroup 的正确方法是什么?

What is the correct way to add a custom component to a reactive form's FormGroup?

我在包装 mat-select 的自定义组件上使用 formControlName 时遇到了很多问题。

现在看来我的自定义控件找不到表单组?即使自定义元素嵌套在 formGroup 下。

我有一个StackBlitz

但是当我将自定义组件嵌套在 formGroup 下时,问题就来了,所有其他控件都可以找到 formGroup,但我的自定义组件似乎无法找到。

<form novalidate [formGroup]="tenantForm">
    <label for="Id">Id</label>: <input class="form-control" formControlName="id" id="Id" name="Id" />
    <custom-component-with-mat-select formControlName="culture" id="Culture" name="Culture"></custom-component-with-mat-select>
</form>

在此示例中,Id 字段可以正常工作,但 Culture 字段会抱怨未嵌套在 FormGroup 中?

错误:formControlName 必须与父 formGroup 指令一起使用。您需要添加一个 formGroup 指令并将现有的 FormGroup 实例传递给它(您可以在 class 中创建一个)。

自定义组件应如何与响应式表单和表单组一起使用?

我最初的问题是不记得导入 ReactiveFormsModule.. 也许我又忘记导入了一些东西?

这是 设计的实现方式吗?还是我缺少更简单的解决方案??

我需要实现控制值访问器吗?? 正如所解释的 here

只是对执行此操作的设计方式感到困惑。

我的组件包装了 angular material 的 mat-select,我想如果我需要将属性放在 mat-select 上或者让我的组件出现,我也很困惑实现控制值访问器?似乎没有任何效果。

控件 formControlName 必须是字符串值。

案例一

formControlName="animationType"

animtationType 起这里的工作是字符串值。

案例二

[formControlName]="'animationType'" 

这是抛出错误,因为 Angular 正在评估 animationType 的值,它是一个数组(在 ts 文件中定义)

案例三

formControlName="{{animationType}}" 

失败的原因与案例 2 相同

修复

如果你想访问 formControlName 然后在 ts 中使用字符串值 例如:

** 在 ts **

public animationControl = "animation";

** 在 html **

<mat-select name="animationType" [formControlName]="'animationControl'" 

我做了一些研究并让它与控制值访问器一起工作:

https://stackblitz.com/edit/mat-select-with-controlvalueaccessor

我使用参数 'formControl' 而不是 'formControlName' 解决了这个问题,如下所示: 输入-date.compoenent.html

<p-calendar [formControl]="control"></p-calendar>

parent.component.html

<input-date [control]="formGroup.controls.date"></input-date>

其中control是input-date.component的输入:

@Input() control: FormControl;