2016-09-02 70 views
1

應用類到d3元件具有angular2一個部件,其中app.component.css定義h-bar類:angular2:從組件的樣式

enter image description here

app.component.ts,d3被用於產生從app.component.css應用類h-bar元件。

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

但是樣式沒有被正確渲染。看着生成的html,我發現d3生成的那些元素中缺少了隨機_ngcontent-baf-1(不知道它是否是module.id)。

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

封裝樣式只適用於由Angular處理的DOM對象。

我建議在此組件上關閉封裝:

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

然而,這會污染您的全局CSS命名空間,所以你的IDS /類應該是唯一的,這個組件。

爲了保持封裝,試試這個:

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]。它可能會有所不同,所以你必須循環查找屬性才能找到合適的屬性。

+0

css正在工作,但是'encapsulation:ViewEncapsulation.None'會帶'module.id'。 – beewest

+0

出了什麼?我在'moduleId'和'encapsulation'之間沒有看到連接編輯:我現在看到了。 '_ngcontent-baf-1'不是'module.id'。 'module.id'基本上是組件的路徑。 '_ngcontent-baf-1'用於提供視圖封裝/模擬陰影。 – j2L4e

+0

對不起,我的意思是'_ngcontent-baf-1'。任何使用角度生成元素的方法'ngFor'然後綁定每個元素的d3數據模型。我仍然想保持封裝的美麗? – beewest