在Angular 4中使用ngIf找不到HTML元素 [英] Plotly in Angular 4 not finding HTML element with ngIf

查看:680
本文介绍了在Angular 4中使用ngIf找不到HTML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个需要图形的角度4应用程序。
对于我正在使用的图 Plotly.js ,它可以正常工作,除非我使用 ngIf

所以我想要做的是:
我有一个div来初始化图。这是第一次。我也有一些过滤器工作得很好。但是我做了一个按钮来切换视图,而不是显示一个图表,我想用图表的值显示一个表格。当我将视图切换回图表时,我得到

所以这里是我的代码的一部分:



部分我的组件:

  public graph:boolean; 
$ b $ public draw():void {
/ *获取数据的代码* /
Plotly.newPlot('graph',this.drawing,layout,options);
}

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

我的HTML部分

 < div * ngIf =graph> 
< div id =graphclass =graph>< / div>
< / div>

< div * ngIf =!graph>
<! - 表格 - >
< / div>


< button class =btn btn-default btn-sm center-block btn-file(click)=switchView()>
< i class =fa fa-eye>< / i>
切换查看
< / button>


解决方案

 来自'@ angular / core'的ChangeDetectorRef}; 

构造函数(private cdRef:ChangeDetectorRef){}

switchView(){
this.graph =!this.graph;
this.cdRef.detectChanges(); //<<<确保绑定更新
if(this.graph){
this.draw();
} else {
/ * tableview * /
}
}


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>

解决方案

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

这篇关于在Angular 4中使用ngIf找不到HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆