Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap an Angular component around a dynamic component

I have an app that needs horizontal scrolling for many different types of lists. It's a music app, so I have horizontal scrolling for album images, featured images, etc. I've generated some html that creates the horizontal scrolling for a list of album items like so:

<div class="hs-grid">
  <div class="hs full"">
      <app-album-item *ngFor="let releaseEl of releases" [submission]="releaseEl"></app-album-item>
  </div>
</div>

Which creates something like this: enter image description here

My question is, how can I convert the grid html in to a component so that I don't have to duplicate the grid code for each of the different types of horizontally scrolling items. Essentially something like:

<app-horizontal-scroll-grid>
    <app-album-item *ngFor="let releaseEl of releases" [submission]="releaseEl"></app-album-item>
    <!-- IT CAN ALSO BE FEATURED ITEMS -->
    <app-featured-item *ngFor="let featuredItem of featured" [featuredItem]="featuredItem"></app-featured-item>
</app-horizontal-scroll-grid>

Obviously this wouldn't work...

How should I pass through the list of items to be used inside the horizontal-grid-component since it can be a different type of component such as:

  • app-album-item
  • app-featured-item
  • etc?

I know that if I only had one type of component I needed to horizontally scroll, I could place the app-album-item inside the horizontal-scroll-grid component HTML and pass through the list of items to an @Input(), but since the type of component changes, I am a little confused!

Thanks for any help/insight!

like image 303
Jordan Lewallen Avatar asked Mar 05 '26 11:03

Jordan Lewallen


1 Answers

The ng-content directive allows to insert components and HTML content dynamically inside another component. This article by Angular University gives more details about content projection in Angular.

You could define the "scroller" component template as:

<div class="hs-grid">
  <div class="hs full"">
    <ng-content></ng-content>
  </div>
</div>

And include other components inside of the scroller in the parent component template:

<app-horizontal-scroll-grid>
  <app-album-item *ngFor="let releaseEl of releases" ...></app-album-item>
</app-horizontal-scroll-grid>

See this stackblitz for a demo.

like image 200
ConnorsFan Avatar answered Mar 08 '26 19:03

ConnorsFan