将formControlName转发到Angular中的内部组件 [英] Forwarding formControlName to inner component in Angular
问题描述
我有一个包装到<ext-some-input>
的自定义控件组件<some-input>
. 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?
已
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;
}
Forked Stackblitz
如果您不知道ControlContainer
(FormGroupDirective
,FormGroupName
或FormArrayName
)提供了哪个指令,则可以使用更通用的方法:
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]]
}
]
Demo
这篇关于将formControlName转发到Angular中的内部组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!