I'm new to Angular and I have a couple Modules
and Components
. I want a child module to import a component. Then have a parent module import the child module and create it's component. And yes, I have exported the Component in the child module.
I want it like so:
But I get the error:
ERROR in parent/parent.module.ts(8,5): error TS2304: Cannot find name 'ToyComponent'.
I do not understand why this is not working. I would appreciate an explanation over some sample code. Thanks!
This is the relevant code:
Toy Component
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-toy',
templateUrl: './toy.component.html',
styleUrls: ['./toy.component.css']
})
export class ToyComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
Toy Component HTML
<p>
Awesome toy!
</p>
Child Module
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ToyComponent } from './toy/toy.component';
import { ChildComponent } from './child.component';
@NgModule({
declarations: [
ToyComponent,
ChildComponent
],
imports: [
CommonModule
],
exports: [
ToyComponent
]
})
export class ChildModule { }
Parent Module
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ChildModule } from './child/child.module';
import { ParentComponent } from './parent.component';
@NgModule({
declarations: [
ToyComponent,
ParentComponent
],
imports: [
ChildModule,
CommonModule
],
exports: [
]
})
export class ParentModule { }
Parent Component HTML
<p>
parent works! Child: Toy: <app-toy></app-toy>
</p>
Fix:
1. Remove ToyComponent
from the declarations and exports of ParentModule
.
2. Declare ToyComponent
in your Child Module
and export it.
3. Add ChildModule
as an import to your parent module.
Reason:
Your ToyComponent
is declared under your ChildModule
. Since you use ToyComponent
in your ParentModule
, you need to export your ToyComponent
from your ChildModule
. And import the ChildModule
in your ParentModule
.