繁体   English   中英

Angular 8:组件内部的 formControlName,使用 formgroupname 替代 ControlValueAccessor 等?

[英]Angular 8: formControlName inside component, Alternative to ControlValueAccessor with formgroupname, etc?

发布了一个问题: Angular 2 - formControlName inside component 然而,真正让我感兴趣的是下面 PMoloney 的回答评论。 好奇它是否有价值或有用吗? 作者 PMaloney 从未指定如何使用它,有人可以提供他的想法的工作示例吗? 我试图弄清楚。

“这个答案有点过时了,Angular 现在有 FormGroupName,它的工作原理类似于 FormControlName,即理论上它不是包装每个输入,而是简单地添加一个指向 FormGroup 的指针”

原始问题: “我想创建一个可以与 FormBuilder API 一起使用的自定义输入组件。如何在组件中添加 formControlName?

<label class="custom-input__label"
          *ngIf="label">
        {{ label }}
</label>
<input class="custom-input__input" 
       placeholder="{{ placeholder }}"
       name="title" />
<span class="custom-input__message" 
      *ngIf="message">
        {{ message }}
</span>

使用目标:

<custom-input label="Title" 
           formControlName="title" // Pass this to input inside the component>
</custom-input>

回答,尤其是评论让我很感兴趣。

“这个答案有点过时了,Angular 现在有 FormGroupName,它的工作原理类似于 FormControlName,即理论上它不是包装每个输入,而是简单地添加一个指向 FormGroup 的指针”

答案: https://stackoverflow.com/a/39696952 “这里的主要思想是您必须将 FormControl 链接到 FormGroup,这可以通过将 FormGroup 传递给每个输入组件来完成......因此您的输入模板可能如下所示:

<div [formGroup]="form">
    <label *ngIf="label">{{ label }}</label>
    <input [formControlName]="inputName" />
    <span *ngIf="message">{{ message }}</span>
</div>

输入组件的@Input 将是表单、label、inputName 和 message。 它将像这样使用:

<form [FormGroup]="yourFormGroup">
    <custom-input
        [form]="yourFormGroup"
        [inputName]="thisFormControlName"
        [message]="yourMessage"
        [label]="yourLabel">
    </custom-input>
</form>

要使用您自己的组件,例如FormControl ,您可以实施接口ControlValueAccessor 指南

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM