angular material 选项卡内容 c3js 图表未显示

angular material tab content c3js chart not showing

我想在 angular material 选项卡中显示图表。但是选项卡初始化似乎是异步的,所以 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

问题

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

解决方案是使用另一个生命周期回调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%')
          }
        }
      }
    });   
  }
}

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