Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select a ContentChild of a native element in Angular 6?

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?

like image 725
Yulian Avatar asked Aug 03 '18 13:08

Yulian


1 Answers

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.

like image 155
Reactgular Avatar answered Nov 14 '22 22:11

Reactgular