首页 文章

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

提问于
浏览
0

我在包装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中?

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).

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

我原来的问题是不记得导入ReactiveFormsModule ..也许我忘了再次导入一些东西?

这是answer设计的方法吗?或者我错过了一个更简单的解决方案?

我需要实现一个控制值访问器吗?正如here所述

只是混淆了设计的方式来做到这一点 .

我的组件包装角度材料的mat-select,我想如果我需要在mat-select上放置属性或让我的组件实现控制值访问器,我也很困惑?似乎什么都没有用 .

2 回答

  • 1

    Control formControlName 必须是字符串值 .

    案例1

    formControlName="animationType"
    

    animtationType 起这个工作在这里是字符串值 .

    案例2

    [formControlName]="'animationType'"
    

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

    案例3

    formControlName="{{animationType}}"
    

    这与案例2的原因相同

    修复

    如果要访问formControlName,请在ts ex中使用字符串值:

    ** in ts **

    public animationControl = "animation";
    

    **在HTML **

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

    我做了一些研究,并使用控制值访问器:

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

相关问题