如何在不同位置呈现指令内部的内容 [英] How to render a content inside directive at various places
问题描述
我想要一个组件指令来呈现放置在其选择器中的所有内容,以呈现在其html中的特定部分.
I want a component directive to render anything put inside it's selector to be rendered at specific sections inside its html.
页眉,页脚,主要.
any.html
<any-selector>
<div>content to place</div>
</any-selector>
期望它呈现以下内容
any-selector.html
any-selector.html
<header><div>content to place</div></header>
<main><div>content to place</div></main>
<footer><div>content to place</div></footer>
使用ng-content
对其进行了尝试,但仅在第一次出现<ng-content>
tried it with ng-content
but it rendered only at first occurrence of <ng-content>
是否有办法实现这一目标?
If there's any way to achieve this?
推荐答案
因此,这是ng-content
的预期行为,您可以将[select]
指向某些ng-content
,也可以仅在第一个ng-content
的出现.
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>
,然后在应用选择器.HTML中,您可以执行以下操作:
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>
应用选择器.component
@ViewChildren("canvas") canvas: QueryList<ElementRef>;
@ContentChild("myProjection") str : ElementRef;
ngAfterViewInit() {
this.canvas.forEach((div: ElementRef) =>
div.nativeElement.insertAdjacentHTML('beforeend', this.str.nativeElement.innerHTML));
}
这篇关于如何在不同位置呈现指令内部的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!