DonkeyBanana
DonkeyBanana

Reputation: 3556

How to reference and use a component from another module in Angular?

In my app.component.html I added new tag for a custom component, so it looks as shown below. The application crashes and the error says that the app-main-menu-bar is unrecognized as a part of this module and asks me to verify that it is. Well, it's not but I still want to use it by importing another module.

<div>
  <app-main-menu-bar></app-main-menu-bar>
  <router-outlet></router-outlet>
</div>

I'm making sure that the menu component is announced to its holder (I've tried both referencing the component itself and also the module where it resides).

import { MainMenuBarComponent } from "./nav/nav.module";
// import { MainMenuBarComponent } from "./nav/main-menu-bar/main-menu-bar.component";

I also made sure that the menu module is announced to the application module.

import { NavModule } from "./nav/nav.module";
import { AppComponent } from "./app.component";
...
@NgModule({
  declarations: [AppComponent],
  imports: [NavModule, ...],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

The component itself is an Angular component with the selector as expected.

import { Component, OnInit } from "@angular/core";
@Component({
  selector: "app-main-menu-bar",
  templateUrl: "./main-menu-bar.component.html",
  styleUrls: ["./main-menu-bar.component.scss"]
})
export class MainMenuBarComponent implements OnInit {
  constructor() { }
  ngOnInit() { }
}

It resides in a module that exports it liek this.

import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { MainMenuBarComponent } from "./main-menu-bar/main-menu-bar.component";

export { MainMenuBarComponent } from "./main-menu-bar/main-menu-bar.component";

@NgModule({
  imports: [CommonModule],
  declarations: [MainMenuBarComponent]
})
export class NavModule { }

I do understand I'm missing something but I can't imagine what.

Upvotes: 2

Views: 8132

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222722

you need to add the MainMenuBarComponent unde exports inside NavModule

@NgModule({
  imports: [CommonModule],
  declarations: [MainMenuBarComponent],
  exports : [MainMenuBarComponent]
})

Upvotes: 3

Related Questions