2017-07-27 111 views
0

角4沒有找到HTML元素我建立的角4應用需要的曲線圖。 對於我使用Plotly.js圖表,這個工作,因爲它應該,但如果我用ngIfPlotly與ngIf

所以我想做的事: 我有至極一個div圖爲initialized.This工作的第一次。我也有一些過濾器的工作只是fine.However我做了一個按鈕來切換視圖,而不是顯示的圖形我想顯示的表與graph.When我切換視圖返回到圖中的值,然後我得到積極找不到div的錯誤。

因此,這裏有我的部分代碼:

我的份的組分:我的HTML的

public graph:boolean; 

public draw():void { 
    /*code to get data to plot*/ 
    Plotly.newPlot('graph', this.drawing, layout, options); 
} 

switchView(){ 
    this.graph = !this.graph; 
    if(this.graph){ 
     this.draw(); 
    } else { 
     /*tableview*/ 
    } 
} 

零件

<div *ngIf="graph"> 
<div id="graph" class="graph"></div> 
</div> 

<div *ngIf="!graph"> 
    <!--Table --> 
</div> 


<button class="btn btn-default btn-sm center-block btn-file" (click)="switchView()"> 
    <i class="fa fa-eye"></i> 
    Switch View 
</button> 
+0

最有可能的角沒能檢測到變化並插入'div'圖。 IMO最乾淨的解決方案將是創建一個接受數據作爲輸入並繪製它的組件。然後你可以用'* ngIf'或CSS來顯示/隱藏它。您也可以手動觸發更改檢測,但我無法保證在調用plot函數之前會發生這種情況。 – dzejdzej

+0

喜@fangio,我試圖用plotly.js與角4,按這個問題(https://stackoverflow.com/questions/48347425/angular-4-with-plotly)。您可以與我們分享我們如何使用plotly.js?謝謝。 –

回答

2
import { ChangeDetectorRef } from '@angular/core'; 

constructor(private cdRef:ChangeDetectorRef){} 

switchView(){ 
    this.graph = !this.graph; 
    this.cdRef.detectChanges(); // <<< ensure the bindings are updated 
    if(this.graph){ 
     this.draw(); 
    } else { 
     /*tableview*/ 
    } 
}