I have a component that uses content projection.
<ng-content select="button">
</ng-content>
I want to do something like this in my component:
@ContentChild('button') button: ElementRef;
However, when I check this.button, it is undefined both in ngAfterViewInit and ngAfterContentInit.
How can I select my content child if it is a native element and not a custom component?
None of the query decorators can select native elements without a reference.
@ViewChild('button')
@ViewChildren('button')
@ContentChild('button')
@ContentChildren('button')
It is not a CSS selector.
The query decorators search the dependency graph for a matching type and select those. A matching type can be a template reference, component or directive.
The recommended approach for selecting specific elements in content is to tag it with a directive.
@Directive({...})
export class MyButtonDirective {}
Now you can query this in your parent component.
@ContentChild(MyButtonDirective) button: MyButtonDirective;
When you use a string value it refers to a template variable reference. Those are written as #someValue and they can be a template ref, component or directive.
<button #myButton></button>
You can now reference the above as
@ViewChild('myButton')
I do not know if this works for ContentChild because of the way views work. A #myButton template variable might not be visible in the parent's dependency graph.
Alternatively, you can inject the ElementRef of the parent component and then use native JavaScript to search for the children you're seeking. This is a bad practice from an Angular perspective, because the idea is to separate your application from the DOM.
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