简体   繁体   中英

Angular How to use Component in another Component

I have 2 components, first one is modules/pages/home/home.component and the second one is modules/pages/home/components/banner I want to use banner component in home component. when i try to use i get this error

  1. If 'app-banner' is an Angular component, then verify that it is part of this module.
  2. If 'app-banner' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. how can i solve this?

From your folder structure it looks like both components should be part of the same module.

So go to home.module.ts or whatever @NgModule you have, and make sure app-banner is part of the declarations array.

Alternatively, if app-banner is part of separate module, be sure to add that other module inside home.module 's import array.

There should be an app.module.ts file in your project, inside it you'll find @NgModule , and then there should be declarations property (it's an array). Try to insert your BannerComponent in there and call your banner component using it's selector in home.component.html .

  1. To use a component "A" this component must be declared in a Module
  2. To use a component "A" in another component "B", the two component can be declared in the same module or in different module (Imagine declare in module "A" and in module "B") but, in this case , the module "A" must be "export" the component "A", and the module "B" must be import the module "A"

In the same module

@NgModule({
  imports: [...],
  declarations: [AComponent,BComponent,...],
})
export class AllInOneModule {}

In different Module

//Module "A"
@NgModule({
  imports: [...],
  declarations: [AComponent,...],
  exports: [AComponent],
})
export class AModule {}

//Module "B"
@NgModule({
  imports: [AModule...],
  declarations: [BComponent,...],
})
export class BModule {}

导入并在 app.moudle.ts 中声明组件后,它可以工作

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