Yurgi
Yurgi

Reputation: 31

Angular2 nested components without dependency injection possible?

The title might be a little misleading, but it is somewhat accurate.

I have three components. There is one parent component (View) and two child components (Accordion and Panel). The two child components are peers of one another. However, I want Panel to display inside of Accordion without having to inject Panel inside of Accordion's directives property. The reason I want to avoid this is because not every Accordion in the application will have a Panel. I thought that I achieved this awhile back when Angular2 was still in beta, but forgot how. I'm using RC.4.

In theory, this would be an ideal implementation:

view.component.html

<accordion title="View">
  <panel></panel>
</accordion>

view.component.ts

...
@Component({
  ...
  directives: [
    Accordion,
    Panel
  ]
})
...

Right now Accordion is rendering, but Panel is not. I can Panel to render separately. No errors are being thrown in the browser's console.

The components are very, very simple right now, so there is not much code to show.

Upvotes: 1

Views: 360

Answers (1)

Yurgi
Yurgi

Reputation: 31

Thanks to @toskv for providing me with reference material.

I ended up needing to use <ng-content></ng-content> as a placeholder for where the nested component would go. In my case, I want all nested Accordion content to go in the Accordion body. I was able to nested multiple Panels with a single ng-content tag.

This works:

accordion.component.html

<div class="panel">
  <div class="panel-heading">
    <h3 (click)="toggle()">{{title}}</h3>
  </div>
  <div class="panel-body" [hidden]="collapsed">
    <ng-content></ng-content>
  </div>
</div>

panel.component.html

<div class="panel">
  <div class="panel-heading">
    <div class="panel-title">
      Title
    </div>
  </div>
  <div class="panel-body">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </div>
</div>

view.component.html

<accordion title="Instances">
  <panel></panel>
  <panel></panel>
</accordion>

Upvotes: 2

Related Questions