I have a few custom directives which are basically designed for <input>
.
And I have a custom component <app-decorated-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>
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 >
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>
All I want to do is transfer all the directives specified on the <app-decorated-input>
to the underlying <input>
.
We can get child component values in the parent component by creating a reference to the child component using the @ref directive in the Parent component. Using the reference instance, you can access the child component values in the parent.
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 {}
and then in your input component
constructor(@Optional() @Self() @Inject(MY_DIRECTIVES) private myDirectives: any[]) {
console.log(myDirectives);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With