Angular2 - Get component light DOM innerHTML / child nodes

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"><!-- the default template --></div> 

I need to somehow set hasTemplate to true if there is HTML inside the <foo>..</foo> .

+5
source share
1 answer
  • You can switch to encapsulation: ViewEncapsulation.Native , then the content will be in the light of the DOM

  • You can add a wrapper element around <div #wrapper><ng-content><ng-content><div> , then you can get elements from the "shadow DOM"

+4
source

Source: https://habr.com/ru/post/1244046/


All Articles