Limit directive to specific host (component) in Angular
Asked Answered
D

2

11

Is is possible to limit which component can have custom directive?

For example:

@Directive({ 
    selector: '[myHighlight]', 
    host: "my-component" //!!!!!!!!!
})
export class HighlightDirective {
    constructor(el: ElementRef) {  //el is my-component - can not be nothing else !!!!
       el.nativeElement.style.backgroundColor = 'yellow';
    }
}

@Component({selector: "my-component"})...

Use case:
I would like to write directive for specific third-party component. I will use that third-party component properties, so directive on another component wouldn't make any sense and would throw errors.

That means that myHighlight on div would be ignored.

Dinny answered 29/9, 2017 at 11:33 Comment(0)
G
26

I know this question is a couple months old, but you can do this in the selector. The selector property is just a css selector, so you should be able to do something like:

@Directive({ 
    selector: 'my-component[myHighlight]'
})

And that would match only my-component tags with myHighlight attribute. If you tried to apply the myHighlight attribute to, lets say, a div tag, you'd end up getting an error in the console like:

Can't bind to 'myHighlight' since it isn't a known property of 'div'
Gershwin answered 18/12, 2017 at 21:37 Comment(0)
G
-1

You don't need use host. In host, you can write what events you want to listen and some other properties like attribute binding. About this, you can read there Angular Directives

In your case, you can check where you bind your directive like in this example:

@Directive({ 
    selector: '[myHighlight]', 
})
export class HighlightDirective {
    constructor(el: ElementRef) { 
       if (el.nativeElement.tagName === "MY-COMPONENT"){
           el.nativeElement.style.backgroundColor = 'yellow';
       } 
    }
}
Grandstand answered 3/10, 2017 at 22:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.