Shared Components in Angular

You have just created a component that is reusable, meaning you intend to use it in multiple places in your application. This is a good thing, of course, having shared components lends itself to encapsulated DRY code.

The Problem

However, you may think that you only need to declare the component in the module you want to use it in.

If you do this, you will receive an error when trying to declare your component in multiple places:

The component is declared by more than one NgModule

The Solution

The solution is to create a module where your component can be declared:

import { NgModule } from '@angular/core';
import { YourComponent} from '../components/your.component';
@NgModule({
  declarations: [
    YourComponent,
  ],
  exports: [
    YourComponent,
  ]
})
export class YourModule { }

The module will then be imported anywhere you want to use the component:

import { ExampleModule } from '../your.module';
@NgModule({
  imports: [
    YourModule
  ]
  ...
})

This provides further encapsulation - adding any necessary dependencies the component might have right to the module.

Now, the module can be imported anywhere you want to use the component with the added bonus of not worrying about the component’s dependencies.


Erik August Johnson is a software developer working with JavaScript to build useful things. Follow them on Twitter.