Tight in Angular 4 not finding HTML element with ngIf

I am creating an angular 4 application that needs a graph. For graphs I use Plotly.js, it works as it should, except when I use ngIf.

So what I want to do: I have a div in which the chart is initialized. This works for the first time. I also have some filters that work very well. 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 the chart, I get an error that the chart cannot find the div.

So here is part 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>
0
source share
1 answer
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*/
    }
}
+2
source

Source: https://habr.com/ru/post/1692432/


All Articles