0

Im trying to solve the following situation:

I have a child component that will be used in multiple parent components but this child component needs to have access to the parent component (namely its parenComponent.constructor information at runtime).

In a structure like this

<BucketComponent>
    <ParentA>
       <ChildComponent>
    </ParentA>
    <ParentB>
       <ChildComponent>
    </ParentB>
<BuccketComponent>

Before this ChildComponent was shared between parents i did the following

ChildComponentCode

component({
  selector: 'childComponent'
})
export class ChildComponent extends BaseClass<model> implements OnInit, OnDestroy {

  constructor(@Inject(ParentComponentClass) parent: Component) {
    super(parent);
  }

and it worked.

But when i tried sharing it as follows :

const token = new InjectionToken<Component>('ParentComponentToken')

component({
  selector: 'childComponent',
providers: [
    { provide: token , useClass: ParentComponentClassA},
    { provide : token , useClass : ParentComponentClassB}]
})
export class ChildComponent extends BaseClass<model> implements OnInit, OnDestroy {

  constructor(@Inject(token) parent: Component) {
    super(parent);
  }

In one of the instances of childcomponent i get the correct reference to its parent but not in the other (looks to me like its always referencing one of the two)

By the way super(parent); is what uses the parentComponent.constructor information.

Additionaly i already tried using the @Self() and @Host before the @Inject() but to no avail.

Any help into how i can make it so that only the parent where child exists is provided/injected is apreciated.

Thank you in advance

Amgg
  • 117
  • 9

1 Answers1

0

Check this guide. The idea that parent components provide info about themselves via DI and the child component injects whatever parent component's instance. The problem here is that parent component can be whatever you can't know in advance so to solve this problem it's better to introduce an abstract base class or interface (and use InjectionToken) and implement it by all parent components to let the child component know what contract to expect.

Maxim Palenov
  • 650
  • 7
  • 17
  • I am sorry for taking so long to get back but what you suggested does in fact work. I was looking allover for an answer and forgot to read the documentation properly. Thank you – Amgg Mar 18 '20 at 13:31