Hello Devs,
In this tutorial, we are going to learn how to create custom directive in angular 10.
In this directive we will add two event one is mouseenter and mouseleave. using that event will change color of button font.
Follow this step by step guide given below:
Create New App
ng new my-module-app
Create Custom Directive
ng generate directive btn
src/app/btn.directive.ts
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';
@Directive({
selector: '[appBtn]'
})
export class BtnDirective {
constructor(
private elementRef: ElementRef,
private renderer: Renderer2
) {
this.setFontColor('red')
}
setFontColor(color: string) {
this.renderer.setStyle(
this.elementRef.nativeElement,
'color',
color
)
}
@HostListener('mouseenter') onMouseEnter() {
this.setFontColor('blue')
}
@HostListener('mouseleave') onMouseLeave() {
this.setFontColor('red')
}
}
Import Module to module.ts file
src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { BtnDirective } from './btn.directive';
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent, BtnDirective ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Update Component HTML File
src/app/app.component.html
<button appBtn>My Button</button>
Run this command:
ng serve
I hope this example helps you.