Home > front end >  Angular How to use Component in another Component
Angular How to use Component in another Component

Time:05-25

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?

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

  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 {}

CodePudding user response:

after import and declare the component in app.moudle.ts it works

  • Related