Sean
Sean

Reputation: 370

Angular ContentChildren(Component) get any type

I know you can get the children by specifying a specific component type @ContentChildren(SpecificComponent) but can I use @ContentChildren(SOMETHING) and get a component regardless of its type, like a generic component?

Upvotes: 9

Views: 4871

Answers (3)

Simon_Weaver
Simon_Weaver

Reputation: 145890

I always create a directive if I need to do this for a list of children:

@Directive({ 
    selector: '[childComponent]',
    standalone: true
})
export class GenericChildDirective { }

Then in the component:

@ContentChildren(GenericChildDirective) children!: QueryList<GenericChildDirective>;

I actually don't think there's a way to do this as originally asked.

Note: This is basically the same as the Angular example https://angular.io/api/core/ContentChildren#tab-pane-example

Upvotes: 0

anth
anth

Reputation: 1894

@Component({
  template: '<ng-content></ng-content>',
})
export class TestComponent implements AfterContentInit {

    constructor(private readonly elementRef: ElementRef) {
    }

    ngAfterContentInit() {
        const element = this.elementRef.nativeElement as HTMLElement;
        // do wathever you want with element.children
    }
}

Upvotes: 4

Sean
Sean

Reputation: 370

Not sure why someone downvoted this without saying why but ended up finding the solution:

@ContentChildren('childComponent') childComponents;

I pass a string into the contentchildren instead of a component. The string allows me to use a reference a selector (#childComponent)

Upvotes: 6

Related Questions