Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing on all directives to a child element of the component

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 >

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>

All I want to do is transfer all the directives specified on the <app-decorated-input> to the underlying <input>.

like image 221
Tabrez Ahmed Avatar asked Oct 27 '17 06:10

Tabrez Ahmed


People also ask

How do you access the child component property in the parent component?

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.


1 Answers

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);
}
like image 85
Günter Zöchbauer Avatar answered Oct 27 '22 15:10

Günter Zöchbauer