Attribute Directives

Never destroy an element from the DOM. You only change properties of that element for example the backgroundColor.

  • It looks like a normal HTML attribute (possibly with data binding or event binding).
  • Only affect / change the element they are added to.

Attribute directives can change the appearance or behavior of DOM elements and Angular components.

Generate Directive

To create a directive, use the CLI command ng generate directive.

ng generate directive highlight

Shortcut

ng g d directives/highlight

The CLI creates src/app/directives/highlight.directive.ts

The @Directive() decorator’s configuration property specifies the directive’s CSS attribute selector, [appHighlight].

import { Directive } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor() { }
}

Import ElementRef from @angular/core. ElementRef grants direct access to the host DOM element through its nativeElement property.

Add ElementRef in the directive’s constructor() to inject a reference to the host DOM element, the element to which you apply appHighlight.

Add logic to the HighlightDirective class that sets the background to yellow.

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
    constructor(private el: ElementRef) {
       this.el.nativeElement.style.backgroundColor = 'yellow';
    }
}

Applying an attribute directive

<p appHighlight>Highlight me!</p>
Was this page helpful?