Open reboottime opened 7 months ago
Directive is an instruction to the DOM, we use directive to
With angular directives, we can encapsulate reusable behaviors— directives can apply attributes, CSS classes, and event listeners to an element.
Angular Directive Types
ngClass
and ngStyle
structural directives are applied they generally are prefixed by an asterisk, , such as ngIf
A step by step guide on building a highlight
directive.
Angular supports generate directive using cli, bellow is the command to generate a directvi
sh ng generate directive highlight
highlight
directiveimport { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@Input() highlightColor: string = 'yellow';
constructor(private el: ElementRef) {}
@HostListener('mouseenter') onMouseEnter() {
this.highlight(this.highlightColor || 'yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight(null);
}
private highlight(color: string | null) {
this.el.nativeElement.style.backgroundColor = color;
}
}
After importing the directive at the AppModule, you can utilize it everywhere inside of the app
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HighlightDirective } from './highlight.directive';
@NgModule({
declarations: [
AppComponent,
HighlightDirective // Add the directive here
],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
<div [appHighlight]="'cyan'">
Hover over me to highlight in cyan.
</div>
<div [appHighlight]="'pink'">
Hover over me to highlight in pink.
</div>
Overview
This article discusses Angular directives, covering:
References