mvermand
mvermand

Reputation: 6117

Access component surrounding ng-content inside parent component

Given the following setup where app-parent is used in app:

parent.component.html (selector: app-parent)

<div class="parent">
   <app-some-logic>
      <ng-content></ng-content>
   </app-some-logic>
</div>

app.component.html

<app-parent>
   <app-child></app-child>
</app-parent>

When creating the child class as follows, the injected parent (AppSomeLogic) will not be found.

@Component({
  selector: 'app-child',
  standalone: true,
  imports: [],
  ...
})
export class AppChild {

  constructor(parent: AppSomeLogic) {
    super(parent);
  }

}

Is it possible to inject AppSomeLogic into AppChild (when AppChild is injected into the ng-content inside AppSomeLogic in AppParent template)?

Upvotes: 0

Views: 71

Answers (1)

Gabriel Pereira
Gabriel Pereira

Reputation: 58

In the expasion panel from material (original code), they use this way to get the accordion parent (if exists):

@Optional() @SkipSelf() @Inject(MAT_ACCORDION) accordion: MatAccordionBase

In the accordion providers:

{
  provide: MAT_ACCORDION,
  useExisting: MatAccordion,
},

And the token:

export const MAT_ACCORDION = new InjectionToken<MatAccordionBase>('MAT_ACCORDION');

As per the comments in the docs, they made this way to prevent circular reference between the panel and accordion.

In this case, its used "MatAccordionBase" that doesnt have all the accordion properties, but prevent the circular reference.

Testing on new project (Angular 17), i have a similar situation like you (i don't need but can reproduce), and it worked:

export class PageHeaderComponent {
  constructor(@Inject(PageComponent) pageComponent: PageComponent) {
    console.log(pageComponent);
  }
}

Based in this HTML structure

<page>
  <page-header>
    <!-- random code -->
  </page-header>
</page>

Logged result

_PageComponent {headerless: false, __ngContext__: 36}

Upvotes: 0

Related Questions