简体   繁体   English

Angular 2-创建一个Tree组件-使用结构指令进行挣扎

[英]Angular 2 - Create a Tree component - Struggling with structural directives

I try to create a tree of divs with a text (will be more complex eventualy) inside with a structural directive.. and it should render something like this, 我尝试用结构指令在文本(最终会更复杂)中创建一个divs树。它应呈现如下所示,

<div>Campaign
  <div>Leaf A</div>
  <div>Leaf B</div>
</div>
<div>Customer
    <div>Parameters</div>
    <div>Segments</div>
    <div>Products</div>
</div>

but so far I get nested divs that are empty 但到目前为止,我得到的嵌套div是空的

here is the html template using that directive 这是使用该指令的html模板

<div *siteMapLeaf="'Campaign'">
     <div *siteMapLeaf="'Leaf A'"></div>
     <div *siteMapLeaf="'Leaf B'"></div>
</div>
<div *siteMapLeaf="'Customer'">
     <div *siteMapLeaf="'Parameters'"></div>
     <div *siteMapLeaf="'Segments'"></div>
     <div *siteMapLeaf="'Products'">
</div>

here is the directive I use: 这是我使用的指令:

@Directive({ selector: '[siteMapLeaf]' })
export class SiteMapDirective
{
    constructor(
        private templateRef: TemplateRef < any > , // content what is inside ng-Template, ie the div referenced by the directive
        private viewContainer: ViewContainerRef
    ) {}

    @Input() set siteMapLeaf(caption)
    {
        let captionView=this.templateRef.createEmbeddedView(caption);
        this.viewContainer.insert(captionView);
    }

}

thanks 谢谢

Your templates don't have any text nodes that would render caption . 您的模板没有任何可显示caption文本节点。 They only consist of empty div element. 它们仅由空div元素组成。

One way to achieve your requirentments is using Renderer2 as follows: 满足要求的一种方法是使用Renderer2 ,如下所示:

@Directive({ 
  selector: '[siteMapLeaf]' 
})
export class SiteMapDirective {
  constructor(
    private renderer: Renderer2,
    private templateRef: TemplateRef <any>,
    private viewContainer: ViewContainerRef
  ) {}

  @Input() set siteMapLeaf(caption) {
    let captionView = this.templateRef.createEmbeddedView({});
    const parentNode = captionView.rootNodes[0];
    this.renderer.insertBefore(
          parentNode, this.renderer.createText(caption), parentNode.firstChild);
    this.viewContainer.insert(captionView);
  }
}

Here's an Stackblitz example 这是一个Stackblitz的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM