Passing on all directives to a child element of the component
Asked Answered
C

2

25

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>.

Carmody answered 27/10, 2017 at 6:13 Comment(4)
Did you find a solution for that?Goggin
Did you ever figure this out?Dm
@dcp3450, not yetCarmody
did anyone any solution?Purism
S
1

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);
}
Stenographer answered 27/10, 2017 at 10:1 Comment(3)
Can you elaborate this a bit more? If I add that in my custom component constructor, I get a cyclic dependency issue. Or are you talking about the native Input element? Then how to pass to the contructor?Goggin
I'd suggest you create a new question with your code that causrs the error.Mown
Well the question is basically the same, just with a ion-input (from ionic2) instead of input. I don't think it's that much about the error, I'm just not sure where to put it.Goggin
P
0

In the constructor of the directive you can do some like.

constructor(
    @Attribute('attributeName') private attributeUno:String, 
    private element:ElementRef
) {
    console.log(this.attributeUno);
}
Photographic answered 27/10, 2017 at 7:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.