将所有指令传递给组件的子元素 [英] Passing on all directives to a child element of the component
问题描述
我有一些自定义指令,这些指令基本上是为<input>
设计的.
我有一个自定义组件<app-decorated-input>
I have a few custom directives which are basically designed for <input>
.
And I have a custom component <app-decorated-input>
在我的应用程序中有很多<app-decorated-input>
和简单的<input>
,其中一些我喜欢使用指令,而其他一些我不喜欢使用.像这样使用指令时,如何将指令传递给基础<input>
:
There are a ton <app-decorated-input>
s along with simple <input>
s in my application for some of which I like to use the directives and for others I don't. How do I pass on the directives to the underlying <input>
when the directive is used like so:
<app-decorated-input directive1 directive2 ></app-decorated-input>
,并且这些指令对基础<input>
的效果与直接在其上使用的效果相同:
and have the same effect of the directives on the underlying <input>
as if it were used directly on it:
<input type="text" directive1 directive2 >
更新:
<app-decorated-input>
内的内容没有多大意义,除了它包含一个<input>
的事实(我已经提到过).其模板看起来类似于:
UPDATE:
What lies inside <app-decorated-input>
is not much of relevance except the fact that it contains an <input>
as I have already mentioned. Its template looks something similar to:
<div> Some decorations here </div>
<div>
<input type="text" {...directives}> <!-- In ReactJS this is done by using {...this.props} -->
</div>
<div> Some decorations here too! </div>
我要做的就是将<app-decorated-input>
上指定的所有指令都转移到基础<input>
.
All I want to do is transfer all the directives specified on the <app-decorated-input>
to the underlying <input>
.
推荐答案
您可以使每个指令都提供自己,就像使用ControlValueAccessor
或验证程序完成
You can make every directive provide itself like it is done with ControlValueAccessor
or validators
export const MY_DIRECTIVES = new InjectionToken<any>('MyDirectives');
export const MY_DIRECTIVE1: Provider = {
provide: MY_DIRECTIVES,
useExisting: forwardRef(() => MyDirective1),
multi: true
};
@Directive({
selector: '....',
providers: [MY_DIRECTIVE1]
})
class MyDirective1 {}
然后在您的输入组件中
constructor(@Optional() @Self() @Inject(MY_DIRECTIVES) private myDirectives: any[]) {
console.log(myDirectives);
}
这篇关于将所有指令传递给组件的子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!