简体   繁体   English

Angular 如何在另一个组件中使用组件

[英]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.我有 2 个组件,第一个是 modules/pages/home/home.component,第二个是 modules/pages/home/components/banner 我想在 home 组件中使用横幅组件。 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.如果 'app-banner' 是一个 Angular 组件,那么验证它是这个模块的一部分。
  2. If 'app-banner' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.如果“app-banner”是一个 Web 组件,则将“CUSTOM_ELEMENTS_SCHEMA”添加到该组件的“@NgModule.schemas”以禁止显示此消息。 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.所以去home.module.ts或任何你有的@NgModule ,并确保app-bannerdeclarations数组的一部分。

Alternatively, if app-banner is part of separate module, be sure to add that other module inside home.module 's import array.或者,如果app-banner是单独模块的一部分,请确保将其他模块添加到home.moduleimport数组中。

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).您的项目中应该有一个app.module.ts文件,在其中您会找到@NgModule ,然后应该有declarations属性(它是一个数组)。 Try to insert your BannerComponent in there and call your banner component using it's selector in home.component.html .尝试在其中插入BannerComponent并使用home.component.html中的选择器调用横幅组件。

  1. To use a component "A" this component must be declared in a Module要使用组件“A”,该组件必须在模块中声明
  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"要在另一个组件“B”中使用组件“A”,这两个组件可以在同一个模块或不同模块中声明(想象在模块“A”和模块“B”中声明)但是,在这种情况下,模块“A”必须“导出”组件“A”,模块“B”必须导入模块“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 中声明组件后,它可以工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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