代码之家  ›  专栏  ›  技术社区  ›  JBoothUA

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

  •  0
  • JBoothUA  · 技术社区  · 7 年前

    在包装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

    是这个吗 answer

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

    只是对设计的方法感到困惑。

    2 回复  |  直到 7 年前
        1
  •  2
  •   JBoothUA    7 年前

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

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

        2
  •  1
  •   Sunil Singh    7 年前

    控制 formControlName 必须是字符串值。

    案例1

    formControlName="animationType"
    

    animtationType 这里是字符串值。

    案例2

    [formControlName]="'animationType'" 
    

    这是投掷误差,因为Angular正在计算 animationType

    案例3

    formControlName="{{animationType}}" 
    

    这个失败的原因和案例2一样

    修复

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

    **在ts中**

    public animationControl = "animation";
    

    **在html中**

    <mat-select name="animationType" [formControlName]="'animationControl'" 
    
        3
  •  0
  •   Moisés Palma Isern    6 年前

    我用参数“formControl”而不是“formControlName”解决了这个问题,如下所示: 输入日期.component.html

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

    父组件.html

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

    @Input() control: FormControl;