2017-07-27 109 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*/ 
    } 
}