angular2:将类应用于组件样式的d3元素

时间:2016-09-02 08:44:37

标签: d3.js angular typescript

在angular2中有一个组件,其中app.component.css定义了类h-bar

enter image description here

app.component.ts中,d3用于生成应用h-bar中的app.component.css类的元素。

d3.select("#container").selectAll("div.h-bar") // <- C
                .data(data) // <- D
                .enter() // <- E
                .append("div") // <- F                
                .attr("class", "h-bar")                
                .append("span"); // <- G    

但是样式尚未正确呈现。查看生成的html,我发现module.id生成的那些元素中缺少随机 _ngcontent-baf-1 (不确定它是d3)。

enter image description here

所以我想将这个属性module.id添加到这些元素:

// Enter
            d3.select("#container").selectAll("div.h-bar") // <- C
                .data(data) // <- D
                .enter() // <- E
                .append("div") // <- F          
                .attr(module.id, "")                      
                .attr("class", "h-bar")                
                .append("span"); // <- G 

不幸的是,错误被抛出,因为module.id是无效的属性名称:

enter image description here

请问好吗?

1 个答案:

答案 0 :(得分:1)

封装样式仅适用于Angular处理的DOM对象。

我建议关闭此组件的封装:

@Component({
  ...,
  encapsulation: ViewEncapsulation.None
})

但是,这会污染您的全局CSS命名空间,因此您的ID /类应该是此组件的唯一。

要保持封装,请尝试以下方法:

  constructor(private hostRef: ElementRef) { }

  ngOnInit() {
    this.ngContentId = '_ngcontent-' + this.hostRef.nativeElement.attributes[1].name.substr(8);
  }

  addStuff(){
    d3.select("#container").selectAll("div.h-bar") // <- C
      .data(data) // <- D
      .enter() // <- E
      .append("div") // <- F          
      .attr(this.ngContentId, "")
      .attr("class", "h-bar")
      .append("span"); // <- G 
  }

如果主机ID始终为attributes[1],我会发现这很快且很脏。它可能会有所不同,因此您必须遍历这些属性才能找到合适的属性。

相关问题