Skip to main content

How do you make a directive shared?

Steps to make a directive shared

  1. Create a SharedModule
  • Create a module that will hold shared components, directives and pipes.
typescript
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HighlightDirective } from './highlight.directive'; @NgModule({ declarations: [HighlightDirective], imports: [CommonModule], exports: [HighlightDirective] // make the directive available to other modules }) export class SharedModule {}
  1. Add the directive to declarations
  • All directives you want to use must be declared in the module's declarations.
  1. Export the directive via exports
  • This makes it available to other modules that import SharedModule.
  1. Import SharedModule into the modules that need it
typescript
import { SharedModule } from './shared/shared.module'; @NgModule({ imports: [SharedModule] }) export class FeatureModule {}

Conclusion: a shared directive is stored in a module that exports it, and becomes available to all modules that import that shared module.

Short Answer

Interview ready
Premium

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