将 formControlName 转发到 Angular 中的内部组件 [英] Forwarding formControlName to inner component in Angular

查看:23
本文介绍了将 formControlName 转发到 Angular 中的内部组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义控件组件,我将它包装到.SomeInput 是封装的,有自己的 API 并支持响应式表单.ExtSomeInput 是作为 SomeInput 的高级包装器创建的.

I have one custom control component <some-input> that i wrapped to <ext-some-input>. SomeInput is encapsulated, has own API and supports reactive forms. ExtSomeInput is created as high-level wrapper over SomeInput.

我有以下 html:

<form [formGroup]="form">
    <ext-some-input formControlName="name">
</form>

ExtSomeInput的html:

<some-input formControlName="_???_"></some-input>

问题是如何将 formControlName 转发到内部的 SomeInput 组件?我需要将表单和内部 formControl 联系起来.这可能吗?

The question is how to forward formControlName to inner SomeInput component? I need to tie the form and inner formControl up. Is this possible?

我用这个问题创建了 stackblitz 项目:这里

I've created stackblitz project with this issue: here

推荐答案

你的内部组件可以接受 @Input controlName 但它不会开箱即用:

Your inner component can take @Input controlName but it won't work out of the box:

错误:formControlName 必须与父 formGroup 指令一起使用.

Error: formControlName must be used with a parent formGroup directive.

为了将您的控件与父 FormGroup 绑定,您可以定义 viewProvider 如下:

In order to tie your control with parent FormGroup you can define viewProvider as follows:

import { Component, Input, OnInit} from '@angular/core';
...
import { ControlContainer, FormGroupDirective } from '@angular/forms';

@Component({
  ...
  viewProviders: [
    {
      provide: ControlContainer,
      useExisting: FormGroupDirective
    }
  ]
})
export class DateWrapperComponent implements OnInit {
    @Input() controlName: string;
}

分叉 Stackblitz

如果您不知道哪个指令作为 ControlContainer(FormGroupDirectiveFormGroupNameFormArrayNamecode>) 您可以使用更通用的方法:

In case you don't know which exactly directive is provided as a ControlContainer(FormGroupDirective, FormGroupName or FormArrayName) you can use more generic approach:

viewProviders: [
  {
    provide: ControlContainer,
    useFactory: (container: ControlContainer) => container,
    deps: [[new SkipSelf(), ControlContainer]]
  }
]

演示

这篇关于将 formControlName 转发到 Angular 中的内部组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆