Angular & Signals (283 Qs)•Part 2: HttpClient, RxJS Observables & Angular Elements (36 - 62)
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 step:
- 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 ,
javascript
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'red';
}
}
- Apply the attribute directive as an attribute to the host element(for example, <p>)
javascript
<p appHighlight>Highlight me!</p>
- Run the application to see the highlight behavior on paragraph element
javascript
ng serve