简体   繁体   中英

Angular 10 referencing components

I'm really confused about Angular - using version 10.

Scenario 1: IF I define a AComponent.ts/html/css and there is NO A.module.ts. So I decide to Declare it and Export it in app.module.ts, can some other module 'B's html use the 'A' selector ( for example or does 'B' have to import app.module.ts?

Scenario 2: Seems perhaps better if I make an A.module.ts that declares and exports AComponent. B.module.ts would have to IMPORT the A.Module. Then the B.html could do the?

Scenario 3: Otherwise, it seems I would have to be sure the AComponent (whether declared in some module or NOT), could be directly referenced from BComponent.ts with an Import AComponent statement at which point B.html could do the?

Is any or all of this right? Please correct me. I'm struggling with a basic Angular 10 app - it's misbehaving.

Thanks, Yogi

Scenario 1:

AppModule

  • Declares/Export: ComponentA

ModuleB

  • Declares: ComponentB

For ComponentB to be able to use ComponentA, the latter has to be accessible from ModuleB, you can either make it accessible in ModuleB by declaring it in ModuleB instead of AppModule this way:

AppModule

  • Import: ModuleB (If AppModule needs to have access to ComponentB/ComponentA) ModuleB
  • Declares: ComponentB/ComponentA

Or Import AppModule in ModuleB which I doubt is what you want to do as AppModule is used as the root module of your application and should not be imported in other modules

Scenario 2:

ModuleA

  • Declares/Export: ComponentA

ModuleB

  • Declares: ComponentB
  • Imports: ModuleA

This makes ComponentA accessible to ComponentB because ModuleB imports ModuleA and thus has access to all its exported components, it already is a way better solution than scenario 1

Scenario 3:

I don't quite get this scenario if you could explain better, it would help me understand the situation more.

General Rule

ComponentA declared in a ModuleA has access to all the components declared in ModuleA or exported from other modules that are imported in ModuleA.

I advise creating a SharedModule where you declare your components that are reusable in multiple modules and import that module wherever you need it, more info in the doc: https://angular.io/guide/sharing-ngmodules

Please note that services work differently

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