Reputation: 3688
I have the following 3 level nested components in my Angular2 Application. (layout/header/search)
layout/
├── header/
│ ├── search/
│ │ ├── search.component.ts
│ │ └── search.component.html
│ ├── header.component.ts
│ └── header.component.ts
├── layout.component.ts
├── layout.component.html
├── layout.component.css
└── layout.module.ts
I'm trying to call the search component inside my header.component.html
but ending with a console error saying
'Error: Uncaught (in promise): Error: Template parse errors:
'app-search' is not a known element:'
...
layout.module.ts
import { CommonModule } from "@angular/common";
import { NgModule } from "@angular/core";
import { layoutRouting } from "./layout.routing";
import { LayoutComponent } from "./layout.component";
import { HeaderComponent } from './header/header.component';
@NgModule ({
declarations: [
LayoutComponent,
HeaderComponent
],
imports: [
CommonModule,
layoutRouting
]
})
export class LayoutModule { }
layout.component.html
<div class="layout">
<app-header></app-header>
</div>
header.module.ts
import { CommonModule } from "@angular/common";
import { NgModule } from "@angular/core";
import { HeaderComponent } from "./header.component";
import { SearchComponent } from './search/search.component';
@NgModule ({
declarations: [
HeaderComponent,
SearchComponent
],
imports: [
CommonModule
]
})
export class HeaderModule { }
header.component.html
<header class="header">
<app-search></app-search>
</header>
As you can see above, I have already imported the SearchComponent
and and declared at @NgModule
If I import the SearchComponent
in layout.module.ts
(which is the parent component of both children), it works as expected without any errors.
I'm generating component using Angular CLI
e.g: ng g c layout/home/search
What I'm doing wrong here? How can i use the search component in header without calling in layout? Please help me.
Upvotes: 2
Views: 1627
Reputation: 214007
header.module.ts
@NgModule ({
declarations: [
HeaderComponent,
SearchComponent
],
imports: [
CommonModule
],
exports: [HeaderComponent] // make it public
})
export class HeaderModule { }
We export the HeaderComponent so other modules that import the HeaderModule can include it in their component templates. In your case LayoutComponent can include app-header in its template
layout.module.ts
@NgModule ({
declarations: [
LayoutComponent
],
imports: [
CommonModule,
HeaderModule, // add here
layoutRouting
]
})
export class LayoutModule { }
See also
Upvotes: 2