Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How in angular detect how many components in ng-content?

Tags:

angular

Now I have two components

//app-row-two
<div>
  <div x-col><ng-content select="[slot=1]"></ng-content></div>
  <div x-col><ng-content select="[slot=2]" ></ng-content></div>
</div>
//app-row-three
<div>
  <div x-col><ng-content select="[slot=1]"></ng-content></div>
  <div x-col><ng-content select="[slot=2]" ></ng-content></div>
  <div x-col><ng-content select="[slot=3]" ></ng-content></div>
</div>

For two and three columns. And when I use it need to write slot="1" etc. Is a way to merge it into one component that detect how many components in ng-content and create columns ?

like image 492
Vla Mai Avatar asked Sep 06 '25 23:09

Vla Mai


1 Answers

Angular has a decorator that enables a component to detect and query the inner children, it's the ContentChildren decorator.

I created a Stackblitz working sample using it to count how many children are inserted inside the ng-content. You can use a directive or a base abstract class.

Here's the Angular Docs link on this approach.

To be detectable, you need to tell Angular how it will find the children, in this case, I am using a directive:

@Directive({ selector: "[option]" })
export class Option {}

@Component({
  selector: "container",
  template: `
    <ng-content></ng-content>
    <strong>I have {{ childrensLength }} childrens</strong>
  `
})
export class ContainerComponent {
  @ContentChildren(Option) options: QueryList<Option>;

  get childrensLength(): number {
    return this.options ? this.options.length : 0;
  }
}
<container>
    <div option>I am queryable!</div>
    <div option>Me too!</div>
    <div option>Me as well...</div>
    <div>I am not queryable</div>
</container>

Output:

Output sample with the rendered result at browser

like image 123
rogerdossantos Avatar answered Sep 09 '25 22:09

rogerdossantos