This repository has been archived by the owner on Mar 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
[Angular Fundamental] Build Angular Directives #29
Comments
What is Angular DirectiveUsage and classificationsDirective 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
|
How to build Angular directivesAttribute directiveA step by step guide on building a Angular supports generate directive using cli, bellow is the command to generate a directvi
import { 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> |
How to build Angular directivesStructure directive |
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Overview
This article discusses Angular directives, covering:
References
The text was updated successfully, but these errors were encountered: