如何在不同位置呈现指令内的内容 [英] How to render a content inside directive at various places

查看:24
本文介绍了如何在不同位置呈现指令内的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个组件指令来渲染放在它的选择器中的任何东西,以便在它的 html 内的特定部分渲染.

页眉、页脚、主要在这种情况下.

any.html

<div>要放置的内容</div></any-selector>

期待它呈现以下

any-selector.html

要放置的内容

<main><div>要放置的内容</div></main><footer><div>要放置的内容</div></footer>

ng-content 尝试过,但它只在第一次出现

时呈现

如果有任何方法可以实现这一目标?

解决方案

所以,这是 ng-content 的预期行为,要么你把 [select] 放到指向某个 ng-content 或者你可以只在 ng-content 的第一次出现时渲染.

我尝试了一种对我有用的方法.这是演示工作代码

<div #myProjection>要放置的内容</div></any-selector>

然后在 app-selector.HTML 中你可以:

<h1>Hello 组件</h1><header><div #canvas></div></header><footer><div #canvas></div></footer>

app-selector.component

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

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?

解决方案

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

这篇关于如何在不同位置呈现指令内的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆