Search code examples
javascripthtmlangulartypescriptangular-directive

How to render a content inside directive at various places


I want a component directive to render anything put inside it's selector to be rendered at specific sections inside its html.

header, footer, main in this case.

any.html

<any-selector>
    <div>content to place</div>
</any-selector>

Expecting it to render following

any-selector.html

<header><div>content to place</div></header>
<main><div>content to place</div></main>
<footer><div>content to place</div></footer>

tried it with ng-content but it rendered only at first occurrence of <ng-content>

If there's any way to achieve this?


Solution

  • So, this is an expected behavior from ng-content, either you put [select] to point to certain ng-content or you can render just on the first occurrence of ng-content.

    I tried a way which has worked for me. Here is the demo working code

    <any-selector>
        <div #myProjection>content to place</div>
    </any-selector>
    
    

    and then in app-selector.HTML you can do :

    <div id='border'>
        <h1>Hello Component</h1>
        <header><div #canvas></div></header>
        <footer><div #canvas></div></footer>
    </div>
    

    app-selector.component

      @ViewChildren("canvas") canvas: QueryList<ElementRef>;
      @ContentChild("myProjection") str : ElementRef;
    
      ngAfterViewInit() {
         this.canvas.forEach((div: ElementRef) => 
             div.nativeElement.insertAdjacentHTML('beforeend', this.str.nativeElement.innerHTML));
       }