If you want to create a own custom directive then you have to follow this steps.
Here, i have created a directive with name fontcolor.directive.ts . its change the color and underline when some mouse event occurs.
First, Generate a directive using Angular CLI using below coomand.
ng generate fontcolor then you push below code.
You can do it manually with below code.
import { Directive, HostListener, ElementRef, Renderer } from ‘@angular/core’;
@Directive({
selector: ‘[appFontcolor]’ // this is name of directive or you can say selector
})
export class FontcolorDirective {
constructor(
private renderer: Renderer,
private el: ElementRef
){}
@HostListener(‘mouseenter’) onMouseEnter() { // event decleare
this.hover(true);
}
@HostListener(‘mouseleave’) onMouseLeave() { // event decleare
this.hover(false);
}
hover(shouldUnderline: boolean){
if(shouldUnderline){
this.renderer.setElementStyle(this.el.nativeElement, ‘text-decoration’, ‘underline’);
this.renderer.setElementStyle(this.el.nativeElement, ‘color’, ‘#EEBA33’);
} else {
this.renderer.setElementStyle(this.el.nativeElement, ‘text-decoration’, ‘none’);
this.renderer.setElementStyle(this.el.nativeElement, ‘color’, ‘#000’);
}
}
}
Next, you import and use the directive on app.module.ts file to use this.
import { FontcolorDirective } from ‘./fontcolor.directive’;
import { FontcolorDirective } from ‘./fontcolor.directive’;
@NgModule({
declarations: [
AppComponent,
BlogComponent,
FontcolorDirective
],
declarations: [
AppComponent,
BlogComponent,
FontcolorDirective
],
Next, you have to use this on component html page using directive selector.
<div appFontcolor> Helloworld !!! </div>
Finally, if you execute this then you can see the output when mouseenter, mouseleave event occurs.
Please follow and like us: