Search code examples
angularcomponentsparent-childwrapperng-content

Get the component (of which I don't know the instance class) from the one passed to <ng-content>


I have this component:

@Component({
selector: 'my-container',
template: `
    <div class="my-container">
        <div #wrapper class="my-container-body">
            <ng-content></ng-content>
        </div>
        <div class="my-container-footer"></div>
    </div>  
`
})
export class MyContainer implements AfterViewInit {
    @ViewChild('wrapped') item: ElementRef;

    ngAfterViewInit() {
        console.log('wrapped item is: ' + this.item.nativeElement);
    }
}

For example they can use my wrapped in the following way:

<my-container>
    <some-component></some-component>
<my-container>

As you can see I can access to wrapped component, using @ViewChild. Instead I would like to access to the component instance that is passed to <ng-content></ng-content>, but maybe it couldn't work because I don't know what is the right type to use since I don't know what kind of component is passed to my wrapper. The same occurs with @ContentChild.

Am I doing something wrong? How to access to properties and methods of the passed component that could be any component?


Solution

  • As you need something exact from the content component (in your case it is a NgControl) it would be more logical to query for control, not the whole component.

    @ContentChild(NgControl) wrappedControl: NgControl;