Let's begin by creating a new file for our directive named text-marker.ts
. Inside it, paste the following code:
[text-marker.ts] import { Directive, ElementRef, Renderer } from '@angular/core'; @Directive({ selector: '[text-marker]' }) export class TextMarker { constructor(element: ElementRef, renderer: Renderer) { renderer.setElementStyle(element.nativeElement, 'text-decoration', 'underline'); } }
To create a directive, we need to import the Directive
decorator function from Angular core. We will also need two more classes named ElementRef
and Renderer
to manipulate the element. They are injected to our directive class from its constructor.
This directive will add styling to the element and decorate the text with an underline.
Let's test this directive by applying it on our app component
template. Open index.ts
and add the following code:
[app.component.ts] import { Component } from '@angular/core'; @Component({ selector: 'app-root', template...