Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit directive to specific host (component) in Angular

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.

like image 582
Makla Avatar asked Sep 29 '17 11:09

Makla


People also ask

Can we use multiple directives in Angular?

As with components, you can add multiple directive property bindings to a host element.

What is @directive in Angular?

What is meant by directives in Angular? Directives are classes that add new behavior or modify the existing behavior to the elements in the template. Basically directives are used to manipulate the DOM, for example adding/removing the element from DOM or changing the appearance of the DOM elements.

Can a component be directive in Angular?

Yes, in Angular 2, Components are a type of Directive. According to the Doc, “Angular components are a subset of directives. Unlike directives, components always have a template and only one component can be instantiated per an element in a template.”

What are the three types of directives in Angular?

The three types of directives in Angular are attribute directives, structural directives, and components.


1 Answers

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'
like image 94
aasukisuki Avatar answered Sep 21 '22 19:09

aasukisuki