Introduction to Angular Directive Selector syntaxes
210331
It is not necessary to enclose the directive’s selector in square brackets. However, if we do so, the directive is a pure Attribute Directive. Actually, a directive’s selector can have various syntax formats, following the syntax of an element of HTML. A general syntax ‘anatomy’ of an HTM element is given below:
<elem class=”myclass” myattr></elem>
Note that ‘elem’ can be either a native HTML DOM element, or an Angular Component.
According the above, we can use various syntaxes (as well as various combinations of them). Let’s see some of them:
Element Selector
import { Directive } from '@angular/core'; @Directive({ selector: 'elem' }) export class MyDirective { constructor() { } }
Class Selector
import { Directive } from '@angular/core'; @Directive({ selector: '.myclass' }) export class MyDirective { constructor() { } }
NB: We cannot target class names that are dynamically inserted into the DOM using an expression binding either via a class binding or NgClass attribute directive
Attribute Selector
import { Directive } from '@angular/core'; @Directive({ selector: '[myattr]' }) export class MyDirective { constructor() { } }
Or Attribute selector with value:
import { Directive } from '@angular/core'; @Directive({ selector: '[myattr=Panos]' }) export class MyDirective { constructor() { } }
NB: As we said before, when we enclose the directive selector name within brackets “[myattr]”, the directive should be used as an attribute directive, otherwise it will be treated as a new HTML element (e.g. as a component).
Combinations of selectors
Moreover, we can use combinations of selectors
Chaining
import { Directive } from '@angular/core'; @Directive({ selector: 'elem[myattr]' }) export class MyDirective { constructor() { } }
or even:
import { Directive } from '@angular/core'; @Directive({ selector: 'elem.myclass[myattr]' }) export class MyDirective { constructor() { } }
Furthermore, we can use OR in selection, using commas:
import { Directive } from '@angular/core'; @Directive({ selector: 'elem,[myattr]' }) export class MyDirective { constructor() { } }
Finally, we can have exclusions in selection using the :not keyword, like that:
import { Directive } from '@angular/core'; @Directive({ selector: 'elem:not(.myclass)[myattr]' }) export class MyDirective { constructor() { } }
That’s it for now!
Thanx for reading!