【问题标题】:use ng2-charts with a loader and AfterViewInit使用带有加载器和 AfterViewInit 的 ng2-charts
【发布时间】:2020-02-04 02:20:44
【问题描述】:

我有一个包含一些图表的网页,现在我正在尝试创建一个非常简单的加载器:

<div *ngIf="loading === true; else elseBlock" class="container">
  <div class="grid-pulse la-3x">
  </div>
</div>
<ng-template #elseBlock>
  <ng-content></ng-content>
</ng-template>  
import { Component, Input, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-loader',
  templateUrl: './loader.component.html',
  styleUrls: ['./loader.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class LoaderComponent {

  @Input() loading = true;
}

它只在标志为真时在组件和加载器之间交换,在标志为假时交换组件。

现在我实现了一些这样的图表:

<app-loader [loading]="loading">
  <canvas
    baseChart
    #canvas
    [labels]="chartLabels"
    [datasets]="chartData"
    [options]="chartOptions"
    [chartType]="chartType">
  </canvas>
</app-loader>
import { Component, Input, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'my-component',
  // ... the other stuff, scss, html
})
export class MyComponent implements OnInit {

  loading = true;
  // more
  // data
  // ....

  ngOnInit(){
    this.httpService.get('/something').subscribe(data => {
      //do something with the data
      this.loading = false; //set loader to false.
    });
  }


}

完美运行,我的loading 变量取决于我所做的http 请求,然后我将变量更改为false,因此我的chart 出现。

问题是,当我将变量更改为 false 时,它​​会开始挂载组件,但我已经停止显示加载程序....因此在图表出现时我看到一个空白区域。

所以问题是: 如何检查图表是否已安装和创建?因为我不想显示那个空白(我会在组件开始渲染时在顶部显示一个假加载器,关于如何完成的任何想法?)

我读到使用AfterViewInit 以某种方式完成此操作,但我可以使用不是我创建的组件访问该信息(在这种情况下)

【问题讨论】:

    标签: javascript angular chart.js ng2-charts


    【解决方案1】:

    我能想到的唯一合乎逻辑的原因 - 在实际处理数据并将其传递到数组之前,您将加载变量更改为 true,如果您使用的是 forEach 循环,请考虑使用 await 或简单的 for 循环。

    【讨论】:

    • 不,数据已经设置好了,加载需要更多秒的是图表,我实际上用固定数据测试了它,它是一样的,当我设置时它正在创建组件标记为 false,因此它会在一段时间内显示为白色。
    • 您可以访问 loaderComponent 吗?因为在你的最后一句话中你说了一些让我怀疑的话。
    • 是的@Yoshy,正如我在我的问题上所写,加载程序是我制作的,这就是我可以分享代码的原因,只是ngIfelse 块为了显示ng-content
    • 考虑在 LoaderComponent 中使用 ngAfterViewInit 并将不同的布尔变量更改为 true,然后使用它来显示画布?
    猜你喜欢
    • 2018-07-24
    • 2018-02-14
    • 2017-12-05
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 2017-02-23
    相关资源
    最近更新 更多