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,
- 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>
)
<p appHighlight>Highlight me!</p>
- Run the application to see the highlight behavior on paragraph element
ng serve
March 17, 2022
274
Read more
What is Angular Framework?
November 04, 2022
AngularWhat is a Angular module?
November 03, 2022
AngularWhat are the steps to use animation module?
October 31, 2022
Angular