简体   繁体   中英

Angular 7 - Getting Component from imported Module

I read all presented questions stack overflow showed me, none of which solved my issue.

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:

  • Parent Module
    • Child Module
      • Component (Toy)

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 .

Problem

It looks like that the import statement for ToyComponent is missing in ParentModule which causes the error.

Fix

  • Since ToyComponent is added to exports in ChildModule it must not be referenced in ParentModule
  • Remove ToyComponent from the declarations -list in ParentModule

The ToyComponent is known to the ParentModule because ChildModule is added to the imports -List.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM