Plotly in Angular 4 not finding HTML element with ngIf

送分小仙女□ 提交于 2019-12-11 08:46:08

问题


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 wich 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>

回答1:


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


来源:https://stackoverflow.com/questions/45352071/plotly-in-angular-4-not-finding-html-element-with-ngif

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!