【问题标题】:d3.select() returns null for a html element inside <ng-template>d3.select() 为 <ng-template> 中的 html 元素返回 null
【发布时间】:2018-05-13 15:42:51
【问题描述】:

我有一个视图,其中包含

内的 元素
<div *ngIf="data == undefined; else elseBlock">
   Sorry no data!
</div>
<ng-template #elseBlock>
   <svg id="areachart" width="100%" height="210"></svg>
</ng-template>

使用 d3,我正在尝试读取 svg 元素的宽度(baseValue),但 d3.select('#areachart') 在代码中返回 null:

export class DrawAreaChart implements AfterViewInit {

    private data;

    constructor(){}

    ngAfterViewInit() {
       this.chartService.getData().subscribe(
           (result) => {
               if (result) {
                  this.data = result;

                  var svg = d3.select("#areachart"),
                  width = +svg.property("width").baseVal.value, /* The code fails here */
                  height = +svg.property("height").baseVal.value;

                  ....
                  ....
               }
           }
       );
    }
    ....
    ....
    ....
}

它抛出错误说-

无法读取 null 的属性“宽度”

请帮忙。

【问题讨论】:

  • 那时你会从 svg 得到什么?
  • svg 当时正在获取空值。

标签: javascript html angular d3.js svg


【解决方案1】:

data 最初为 null,但在 this.data = result 之后,Angular 在 d3 尝试选择之前没有时间调整 DOM(因此实际上 svg 仍然不在框架中)。

您可以在 ngOnChanges 上运行 d3 代码

ngOnChanges(changes: SimpleChanges) {
  if(changes.data) {
    // d3 code here
  }
}

或者也许在 svg div 上使用[hidden]="!data"(尽管对此有一些警告,请参阅What is the equivalent of ngShow and ngHide in Angular2)。

【讨论】:

  • 感谢理查德的解释。 ngOnChanges 对我不起作用,尽管我可以使用 hidden 属性来做到这一点。
猜你喜欢
  • 1970-01-01
  • 2019-05-05
  • 1970-01-01
  • 2018-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多