Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - Get component light DOM innerHTML / child nodes

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.

like image 925
Michael Bromley Avatar asked Sep 25 '22 05:09

Michael Bromley


1 Answers

  • 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"

like image 116
Günter Zöchbauer Avatar answered Sep 28 '22 05:09

Günter Zöchbauer