0
0
Angularframework~5 mins

Declarations, imports, and exports in Angular

Choose your learning style9 modes available
Introduction

Declarations, imports, and exports help organize Angular apps by telling Angular what parts belong where. This keeps your app neat and working well.

When you create a new component, directive, or pipe to use inside a module.
When you want to use features from another module in your current module.
When you want to share components or directives with other modules.
When you want to keep your app modular and easy to maintain.
When you want to control what parts of a module are visible outside it.
Syntax
Angular
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 {}

declarations list components, directives, and pipes that belong to this module.

imports list other modules whose features you want to use here.

Examples
This module declares two components but only shares HeaderComponent with others.
Angular
@NgModule({
  declarations: [HeaderComponent, FooterComponent],
  imports: [CommonModule],
  exports: [HeaderComponent]
})
export class SharedModule {}
This module uses SharedModule features but does not share anything itself.
Angular
@NgModule({
  declarations: [DashboardComponent],
  imports: [SharedModule],
  exports: []
})
export class DashboardModule {}
Sample Program

This is a simple Angular module. It declares two components: AppComponent and HelloComponent. It imports BrowserModule to run in a browser. It exports HelloComponent so other modules can use it. The app starts with AppComponent.

Angular
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

@NgModule({
  declarations: [AppComponent, HelloComponent],
  imports: [BrowserModule],
  exports: [HelloComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}
OutputSuccess
Important Notes

Only components, directives, and pipes go in declarations.

Modules go in imports and exports.

Exports make parts available outside the module.

Summary

Declarations tell Angular what belongs inside a module.

Imports bring in features from other modules.

Exports share parts with other modules.