InterviewHubPRO
Section Overview
Q62

Question 62 of 283

Part 2: HttpClient, RxJS Observables & Angular Elements (36 - 62)

22%
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:

  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 ,
javascript
 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>)
javascript
 <p appHighlight>Highlight me!</p>
  1. Run the application to see the highlight behavior on paragraph element
javascript
 ng serve