How to render a content inside directive at various places

蹲街弑〆低调 提交于 2020-04-16 02:32:06

问题


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?


回答1:


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));
   }



来源:https://stackoverflow.com/questions/60761677/how-to-render-a-content-inside-directive-at-various-places

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!