Angular 4 Directive selector to target an element inside a component only
Asked Answered
S

3

10

How to target a specific element inside a component in Angular Directive.
I have a component with selector "highlighter". This component has content project using ng-content.
There is a directive with selector "highlighter input".
I believe this directive should get applied to any input only inside the highlighter component only but it gets applied to all the inputs in the application - whats wrong?

Plunker: https://plnkr.co/edit/4zd31C?p=preview

@Component({
  selector: 'highlighter',
  template: `
    This should be highlighted: 
    <ng-content></ng-content>
  `
})
export class HighlighterComponent {
}

@Directive({
  selector: 'highlighter input'
})
export class HighlightDirective {
    constructor(el: ElementRef) {
       el.nativeElement.style.backgroundColor = 'yellow';
    }
}
Selfidentity answered 14/1, 2018 at 22:58 Comment(0)
E
9

Selectors in Angular don't support combinators:

- descendant selector (space)
- child selector (>)
- adjacent sibling selector (+)
- general sibling selector (~)

So the last distinct selector in the string wins, which is input in your case. That's why it's applied to all inputs.

Another thing is that projected content is not considered to be located inside a component to which is projected. So even if Angular supported combinator selectors, the selector highlighter input still shouldn't work.

The simplest solution would be to add a class to the input like this:

<input class="highlighter">

and target this class in the selector:

@Component({
  selector: 'input.highlighter'
Edessa answered 15/1, 2018 at 6:14 Comment(1)
I made a page where you can test how your directive selector is parsed by angular compiler, that's really weird : ydomenjoud.github.io/angular-selector-parserGarretson
H
2

One clue that I found in the Angular doc is that:

Angular only allows directives to trigger on CSS selectors that do not cross element boundaries.

Housekeeping answered 16/1, 2018 at 18:3 Comment(1)
meaning what exactly?Sinecure
S
0

Directives will be applied to all selectors within the module it is declared.

Stab answered 14/1, 2018 at 23:7 Comment(2)
directives should be applied based on directive selector! How is selector read in this case?Selfidentity
Lol. Directive can not be applied to a selector. What it even means to apply a directive to selector? :DPaulettepauley

© 2022 - 2024 — McMap. All rights reserved.