【问题标题】:How to render a content inside directive at various places如何在各个地方呈现指令内的内容
【发布时间】:2020-06-30 20:29:21
【问题描述】:

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

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

任何.html

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

期待它呈现以下内容

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 尝试过,但它只在第一次出现&lt;ng-content&gt; 时呈现

如果有什么方法可以做到这一点?

【问题讨论】:

  • 你试过ng-content的实现是什么?你能分享实现而不是仅仅分享sn-ps吗?或者更好地创建一个小提琴?
  • @Ajeet:你试过我的答案了吗?
  • @ShashankVivek 是的,天哪,我所做的唯一改变是使用outerHTML insted of innerHTML。谢谢! :)

标签: javascript html angular typescript angular-directive


【解决方案1】:

因此,这是 ng-content 的预期行为,您可以将 [select] 指向某个 ng-content,或者您可以仅在第一次出现 ng-content 时呈现。

我尝试了一种对我有用的方法。 Here is the demo working code

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

然后在 app-selector.HTML 你可以这样做:

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

【讨论】:

    猜你喜欢
    • 2015-12-07
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多