Let's say I have a component:
@Component({
selector: 'foo',
template: '<div>foo</div>'
})
export class Foo {}
And I consume it in another component like this:
<foo>
<h1>some inner HTML</h1>
</foo>
How can I find out if Foo
has any child elements in the light DOM?
I want to get ahold of <h1>some inner HTML</h1>
.
Option 1 - @ContentChildren()
: This cannot be used to query arbitrary elements; currently only Angular 2 components or variables (#foo
) may be queried in this way. I don't want to have to attach a variable to the inner elements if I can avoid it.
Option 2 - elementRef.nativeElement
: I can inject ElementRef
into the Foo
component, but by the time the component has instantiated (in the constructor), the inner elements have already been removed, and it will be empty. Later in the life cycle (e.g. ngAfterViewInit()
) the inner elements will just be the shadow DOM (i.e. <div>foo</div>
).
Any other methods that I am missing?
Use Case
To give some context about why I want to do this, I am creating a library component which has a default template, which may be replaced by a custom template if the user decides. So my default template looks like this:
<div *ngIf="hasTemplate"><ng-content></ng-content></div>
<div *ngIf="!hasTemplate"><!-- the default template --></div>
I need some way to set hasTemplate
to true
if there is HTML inside the <foo>..</foo>
tags.
You can switch to encapsulation: ViewEncapsulation.Native
then the content will be in the light DOM
You can add a wrapper element around <div #wrapper><ng-content><ng-content><div>
then you can get the elements from the "shadow 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