POV
POV

Reputation: 12025

How to make component global in Angular 2?

I tried to make component as global. But it returns me an error:

Uncaught Error: Can't export directive LanguageComponent from SharedModule as it was neither declared nor imported!

So, I added component to shareModule as:

exports: [
    LoaderComponent,
    LanguageComponent
  ]

Also I tried to add component to core.module as diclaration. It did not help.

ShareModule is:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LoaderComponent } from './loader/loader.component';
import {LanguageComponent} from "../language/language.component";
import {HiderPipe} from "../pipes/Hider";

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [
    LanguageComponent,
    LoaderComponent,
    HiderPipe
  ],
  exports: [
    LoaderComponent,
    LanguageComponent,
    HiderPipe

  ]
})
export class SharedModule { }

This module is imported only in main core.module as:

@NgModule({
  imports: [

    SharedModule
  ],

Upvotes: 1

Views: 6355

Answers (2)

cyr_x
cyr_x

Reputation: 14267

To make a component available to the module which imports the SharedModule, you have to add the LanguageComponent to the declarations field of your SharedModule and to the exports field.

@NgModule({
  imports: [
    // ...
  ],
  declarations: [
    // ...
    LanguageComponent
  ],
  exports: [
    // ...
    LanguageComponent
  ]
})
export class SharedModule {
  // ...
}

As the error stated, you missed to add it to the declarations field:

Uncaught Error: Can't export directive LanguageComponent from SharedModule as it was neither declared nor imported

Or if you LanguageComponent is already part of another module (for example: LanguageModule), you have to import that module and you can also reexport that module.


To use the component in another component which is part of another module, for example AppModule, you have to add the SharedModule to the import field of that module.

@NgModule({
  imports: [
    // ...
    SharedModule
  ],
  declarations: [
    // ...
  ],
  exports: [
    // ...
  ]
})
export class AppModule {
  // ...
}

And use it inside your component's template via the selector. See also the Feature Module section at the docs.

Upvotes: 4

JSingh
JSingh

Reputation: 375

You also need to add in declarations array.

declarations:[LanguageComponent]

Upvotes: 1

Related Questions