Give an example for attribute directives?

Let's take simple highlighter behavior as a example directive for DOM element. You can create and apply the attribute directive using below steps,

  1. Create HighlightDirective class with the file name src/app/highlight.directive.ts. In this file, we need to import Directive from core library to apply the metadata and ElementRef in the directive's constructor to inject a reference to the host DOM element ,
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appHighlight]',
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'red';
}
}
  1. Apply the attribute directive as an attribute to the host element(for example, <p>)
<p appHighlight>Highlight me!</p>
  1. Run the application to see the highlight behavior on paragraph element
ng serve

March 17, 2022
273