Custom Directive
Create a custom directive to highlight text:
ng generate directive highlight
Implement the directive in src/app/highlight.directive.ts
:
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) { }
@HostListener('mouseenter') onMouseEnter() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor');
}
}
Use it in a component template:
<p appHighlight>This text will be highlighted on hover.</p>
Custom Pipe
Create a custom pipe to transform text to uppercase:
ng generate pipe uppercase
Implement the pipe in src/app/uppercase.pipe.ts
:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'uppercase'
})
export class UppercasePipe implements PipeTransform {
transform(value: string): string {
return value.toUpperCase();
}
}
Use it in a component template:
<p>{{ 'hello world' | uppercase }}</p>
Leave a Reply