Skip to main content

How do you register a directive in a module?

To register a directive in Angular, you need to add it to the module's declarations array (NgModule).

Example:

typescript
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { HighlightDirective } from './highlight.directive'; @NgModule({ declarations: [ AppComponent, HighlightDirective // register the directive here ], imports: [ BrowserModule ], bootstrap: [AppComponent] }) export class AppModule { }

After that, the directive becomes available in all components of this module and can be applied to elements through its selector.

Conclusion: a module's declarations array is where all components, directives and pipes are registered so Angular can recognize them.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.