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 ?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With