角度材料选项卡内容c3js图表未显示

时间:2018-02-16 15:44:38

标签: angular typescript tabs angular-material c3.js

我想在角度材质标签中显示图表。但是标签初始化似乎是异步的,所以c3js找不到div #detailed-chart而我的标签仍然是空的。

模板

<mat-card class="col-xs-12">
  <mat-card-title>
    Detailed Utilization
  </mat-card-title>

  <mat-tab-group>
    <mat-tab label="Chart">
      <div id="detailed-chart" style="height: 200px"></div>
    </mat-tab>
    <mat-tab label="Table">
    </mat-tab>
  </mat-tab-group>
</mat-card>

组件

export class UtilizationComponent implements OnInit {
  ngOnInit() {       
    this.detailedChart = c3.generate({
      bindto: '#detailed-chart',
      data: {
        x: 'date',
        columns: [
          ['date'],
          ['room'],
          ['desk'],
          ['office']
        ]
      },
      axis: {
        x: {
          type: 'timeseries',
          tick: {
            format: '%m.%Y'
          }
        },
        y: {
          tick: {
            format: d3.format('.1%')
          }
        }
      }
    });   
  }

}

我也尝试手动找到div,但似乎不存在。

const x = window.document.getElementById('detailed-chart');
console.log('foo', x);

输出

  

foo null

问题

在这里加载动态元素的方法是什么?我是否需要为此选项卡创建单独的组件?

2 个答案:

答案 0 :(得分:0)

解决方案是使用另一个生命周期回调ngAfterViewInit

export class UtilizationComponent implements AfterViewInit {
  ngAfterViewInit() {       
    this.detailedChart = c3.generate({
      bindto: '#detailed-chart',
      data: {
        x: 'date',
        columns: [
          ['date'],
          ['room'],
          ['desk'],
          ['office']
        ]
      },
      axis: {
        x: {
          type: 'timeseries',
          tick: {
            format: '%m.%Y'
          }
        },
        y: {
          tick: {
            format: d3.format('.1%')
          }
        }
      }
    });   
  }
}

答案 1 :(得分:0)

您可以使用回调AfterViewChecked来显示图表。