简体   繁体   中英

use ng2-charts with a loader and AfterViewInit

I have a web page which has some charts, right now I'm trying to create a loader which is very simple:

<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;
}

which only swap between a component and a loader while the flag is true and the component when it is false.

now I implemented some of the charts like this:

<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.
    });
  }


}

which work perfectly, my loading variable depends on a http request that I do, and then I change the variable to false and therefore my chart appears.

the problem is that when I change my variable to false, it starts to mount the component, but I already stopped showing the loader.... therefore I see a blank space while the chart is appearing.

so the question is: how can I check if the chart was already mounted and created? because I don't want to show that white space (I'll show a fake loader on top while the component starts rendering, any Ideas on how to accomplish?)

I read that someway to accomplish this is with AfterViewInit but can I access that information with a component that is not created by me (in this case )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM