1

I am building an angular 4 App that needs a graph. For graphs I am using Plotly.js, this works as it should, except if I use ngIf.

So what I want to do: I have a div in which the graph is initialized. This works the first time. I also have some filters that work just fine. However I made a button to switch the view, instead of showing a graph I want to show a table with the values of the graph. When I switch the view back to graph, then I get the error that plotly cannot find the div.

So here are parts of my code:

Parts of my component:

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*/
    }
}

Parts of my HTML

<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>
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
fangio
  • 1,746
  • 5
  • 28
  • 52
  • Most likely Angular did not manage to detect change and insert the graph `div`. IMO the cleanest solution would be to create a component which accepts data as input and plots it. You can then show/hide it with `*ngIf` or with CSS. You can also trigger the change detection manually but I cannot guarantee it will happen before plot function is called. – jacekbj Jul 27 '17 at 13:33
  • hi @fangio , I am trying to use plotly.js with Angular 4, as per this question(https://stackoverflow.com/questions/48347425/angular-4-with-plotly). Can you share with us on how can we use plotly.js? Thanks. – Afeez Aziz Jan 21 '18 at 13:44

1 Answers1

3
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*/
    }
}
fangio
  • 1,746
  • 5
  • 28
  • 52
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567