Say I have a component:
@Component({ selector: 'foo', template: '<div>foo</div>' }) export class Foo {}
And I use it in the following component:
<foo> <h1>some inner HTML</h1> </foo>
How to find out if there are Foo
children in the light of the DOM?
I want to get <h1>some inner HTML</h1>
.
Option 1 - @ContentChildren()
: this cannot be used to request arbitrary elements; currently only Angular 2 components or variables ( #foo
) can be requested. I do not want to apply a variable to internal elements if I can avoid it.
Option 2 is elementRef.nativeElement
: I can insert ElementRef
into the Foo
component, but by the time the component is instantiated (in the constructor) the internal elements are already deleted and it will be empty, Later in the life cycle (for example, ngAfterViewInit()
) the internal elements will simply shadow DOM (i.e. <div>foo</div>
).
Any other methods that I am missing?
Use case
To give some context why I want to do this, I create a library component that has a default template that can be replaced with a user template if the user decides. So my default template is as follows:
<div *ngIf="hasTemplate"><ng-content></ng-content></div> <div *ngIf="!hasTemplate"></div>
I need to somehow set hasTemplate
to true
if there is HTML inside the <foo>..</foo>
.
source share