Angular Standalone components 02: Standalone Directives

Yuvaraj S
2 min readAug 21, 2023

--

In my previous blog we discussed about how to create a standalone component.

Today we will see how to create a stand alone directive.
I have created a highlight directive. where if we attach the directive in the component.html, we will be seing highlighted html block.

import { Directive, ElementRef } from '@angular/core';

@Directive({
selector: '[appHighlight]',
})
export class HighlightDirective {
constructor(private element: ElementRef) {
this.element.nativeElement.style.backgroundColor = '#5f5aee';
this.element.nativeElement.style.color = 'black';
this.element.nativeElement.style.padding = '0.5rem';
}
}

Now, in order to make stand alone directive we will have to write add a configuration object as standalone: true.

import { Directive, ElementRef } from '@angular/core';

@Directive({
standalone:true,
selector: '[appHighlight]',
})
export class HighlightDirective {
constructor(private element: ElementRef) {
this.element.nativeElement.style.backgroundColor = '#5f5aee';
this.element.nativeElement.style.color = 'black';
this.element.nativeElement.style.padding = '0.5rem';
}
}

once we do stand alone true, we should remove it in the declaration section in app.module.ts or any of the module we are using it as a directive. instead of declaring it in a declaration section. we will declare it in a imports section.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { HighlightDirective } from './highlight.directive';

@NgModule({
imports: [BrowserModule, FormsModule, HighlightDirective],
declarations: [AppComponent, HelloComponent],
bootstrap: [AppComponent],
})
export class AppModule {}

And there we go we have made it, now the directive will work as stand alone.

Find the stackblitz link here
https://stackblitz.com/edit/angular-15-starter-project-oo3q2x

UP NEXT

Angular standalone component 03: Migrate App module to standalone

— — — — — — — — — End Of Lecture — — — — — — —

Check All lessons of Angular Intermediate Lessons

https://medium.com/@yuvayuvaraj720444/angular-intermediate-lessons-acbea2dfc9b

--

--

Yuvaraj S

Passionate Angular Developer. I post programming content regarding, Frontend Development with working example. ie, Angular, Html, CSS, Javascript