Angular 2 - 创建树组件 - 与结构指令作斗争

Angular 2 - Create a Tree component - Struggling with structural directives

我尝试创建一个 div 树,里面有一个文本(最终会更复杂) 有一个结构指令..它应该呈现这样的东西,

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

但到目前为止我得到的嵌套 div 是空的

这是使用该指令的 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>

这是我使用的指令:

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

}

谢谢

您的模板没有任何可以呈现的文本节点 caption。它们只包含空 div 元素。

实现您的要求的一种方法是使用 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);
  }
}

这是一个Stackblitz example