How to Use Exports in Angular Module: Simple Guide
In Angular, use the
exports array inside an @NgModule to make components, directives, or pipes available to other modules. Anything listed in exports can be used by modules that import this module.Syntax
The exports array is part of the @NgModule decorator. It lists components, directives, or pipes that you want to share with other modules.
Structure:
declarations: Declare components, directives, pipes used internally.exports: Export those declarations you want other modules to use.imports: Import other modules needed.
typescript
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MyComponent } from './my-component.component'; @NgModule({ declarations: [MyComponent], imports: [CommonModule], exports: [MyComponent] }) export class MyModule {}
Example
This example shows a module that declares and exports a component. Another module imports it to use the exported component.
typescript
import { NgModule, Component } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; @Component({ selector: 'app-greeting', template: '<h1>Hello from Greeting Component!</h1>' }) export class GreetingComponent {} @NgModule({ declarations: [GreetingComponent], exports: [GreetingComponent] }) export class SharedModule {} @Component({ selector: 'app-root', template: '<app-greeting></app-greeting>' }) export class AppComponent {} @NgModule({ declarations: [AppComponent], imports: [BrowserModule, SharedModule], bootstrap: [AppComponent] }) export class AppModule {}
Output
Hello from Greeting Component!
Common Pitfalls
Common mistakes include:
- Not exporting a declared component, so it can't be used outside the module.
- Trying to export something not declared or imported in the module.
- Forgetting to import the module that exports the component in the consuming module.
typescript
/* Wrong: Component declared but not exported */ @NgModule({ declarations: [MyComponent], exports: [] // MyComponent missing here }) export class MyModule {} /* Right: Export the component to share it */ @NgModule({ declarations: [MyComponent], exports: [MyComponent] }) export class MyModule {}
Quick Reference
Exports array in Angular module:
- Lists components, directives, pipes to share.
- Must be declared or imported in the module.
- Modules importing this module can use exported items.
Key Takeaways
Use the exports array in @NgModule to share components, directives, or pipes with other modules.
Only declarations or imported modules can be exported.
Import the module that exports components to use them in another module.
Forgetting to export a declared component prevents it from being used outside its module.
Exports do not re-declare components; they only make them available externally.