0 votes
in Angular by

Give an example for attribute directives?

1 Answer

0 votes
by

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 ,

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 appHighlight>Highlight me!</p>

Run the application to see the highlight behavior on paragraph element

ng serve

Related questions

+2 votes
asked Jul 5, 2022 in Angular by sharadyadav1986
+2 votes
0 votes
asked Feb 5, 2021 in Angular by SakshiSharma
...