basic-highlight.directive.ts
import {Directive, ElementRef, OnInit} from '@angular/core'; @Directive({ selector: '[appBasicHighlight]' }) export class BasicHighlightDirective implements OnInit { constructor(private elementRef: ElementRef) { } ngOnInit(): void { this.elementRef.nativeElement.style.backgroundColor = 'red'; } }
better-highlight.directive.ts
Using the Renderer to build a Better Attribute Directive
import {Directive, ElementRef, OnInit, Renderer2} from '@angular/core'; @Directive({ selector: '[appBetterHighlight]' }) export class BetterHighlightDirective implements OnInit { constructor(private elementRef: ElementRef, private renderer: Renderer2) { } ngOnInit(): void { // use this in environments that DOM is not directly accessible like cordova apps this.renderer.setStyle(this.elementRef.nativeElement, 'background-color', 'blue'); } }
app.component.html
<p appBasicHighlight>Hello World</p> <p appBetterHighlight>Hello World 2</p>
References
https://github.com/mhdr/AngularSamples/tree/master/016/my-app