How do you make a directive shared?
Steps to make a directive shared
- 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 {}- Add the directive to
declarations
- All directives you want to use must be declared in the module's
declarations.
- Export the directive via
exports
- This makes it available to other modules that import
SharedModule.
- 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 readyPremium
A concise answer to help you respond confidently on this topic during an interview.