OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Angular Chart.js Charts Not Updating on Data Change Until Console is Opened

  • Thread starter Thread starter John Smith
  • Start date Start date
J

John Smith

Guest
I am working on an Angular application using Chart.js to render charts. The charts initially render correctly, but they do not update when the data changes unless I open the browser's console.

Here are the relevant parts of my component:

Code:
import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  OnDestroy,
  OnInit,
  ViewChild,
} from "@angular/core";
import { Subject, takeUntil } from "rxjs";
import { KafkaAnalyticsService } from "../kafka-analytics.service";
import { UserService } from "app/core/user/user.service";
import { ChartData, ChartType, BaseChartDirective } from "ng2-charts";

@Component({
  selector: "app-kafka-analytics-list",
  templateUrl: "./kafka-analytics-list.component.html",
  styleUrls: ["./kafka-analytics-list.scss"],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class KafkaAnalyticsListComponent implements OnInit, OnDestroy {
  @ViewChild('lineChart') lineChart: BaseChartDirective;
  @ViewChild('barChart') barChart: BaseChartDirective;

  private _unsubscribeAll: Subject<any> = new Subject<any>();

  public TicketLineChartData: ChartData<"line"> = {
    labels: [],
    datasets: [],
  };

  public TicketBarChartData: ChartData<"bar"> = {
    labels: [],
    datasets: [],
  };

  constructor(
    private _changeDetectorRef: ChangeDetectorRef,
    private _kafkaAnalyticsService: KafkaAnalyticsService,
    private _userService: UserService
  ) {}

  ngOnInit(): void {
    this._kafkaAnalyticsService.kafkaTickets$
      .pipe(takeUntil(this._unsubscribeAll))
      .subscribe((response) => {
        if (response) {
          this.updateCharts(response);
          // Ensure Angular detects changes
          this._changeDetectorRef.markForCheck();
        }
      });
  }

  ngOnDestroy(): void {
    this._unsubscribeAll.next(null);
    this._unsubscribeAll.complete();
  }

  updateCharts(response): void {
    // Process response and update chart data
    // ...

    if (this.lineChart) {
      console.log('Updating line chart');
      this.lineChart.update();
    } else {
      console.log('Line chart is not available');
    }

    if (this.barChart) {
      console.log('Updating bar chart');
      this.barChart.update();
    } else {
      console.log('Bar chart is not available');
    }
  }

  getTicketsTime(time): void {
    // Logic to get tickets based on time
    // ...
    this._kafkaAnalyticsService.updateTickets(startDate, endDate)
      .pipe(takeUntil(this._unsubscribeAll))
      .subscribe();
  }
}

The HTML Template:

Code:
                Kafka Tickets ({{time}})

                
              </div>
              <div class="text-secondary font-medium">Trend of Kafka tickets opened</div>
            </div>

            <div class="mt-3 sm:mt-0 sm:ml-2">
              <button class="justify-items-end" mat-flat-button [color]="'primary'" [disabled]="isLoading"
                  [matTooltip]="'Submit'" [matMenuTriggerFor]="timeMenu">
                  Select Time
                </button>
                <mat-menu #timeMenu="matMenu">
                  <button mat-menu-item *ngFor="let time of date_selection" [value]="time"
                    (click)="getTicketsTime(time)">
                    {{ time }}
                  </button>
                </mat-menu>
            </div>
          </div>
          <div class="flex flex-col flex-auto mt-6">
            <canvas baseChart class="lineChart" [data]="TicketLineChartData" [type]="lineChartType"></canvas>
          </div>
          <div class="flex flex-col flex-auto mt-6">
            <canvas baseChart class="barChart" [data]="TicketBarChartData" [type]="barChartType"> </canvas>
          </div>
        </div>
      </ng-template>

The charts when initially loading onto the page are perfect, but when selecting a new time, they do not update unless going to the console.

<p>I am working on an Angular application using Chart.js to render charts. The charts initially render correctly, but they do not update when the data changes unless I open the browser's console.</p>
<p>Here are the relevant parts of my component:</p>
<pre><code>import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
OnDestroy,
OnInit,
ViewChild,
} from "@angular/core";
import { Subject, takeUntil } from "rxjs";
import { KafkaAnalyticsService } from "../kafka-analytics.service";
import { UserService } from "app/core/user/user.service";
import { ChartData, ChartType, BaseChartDirective } from "ng2-charts";

@Component({
selector: "app-kafka-analytics-list",
templateUrl: "./kafka-analytics-list.component.html",
styleUrls: ["./kafka-analytics-list.scss"],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class KafkaAnalyticsListComponent implements OnInit, OnDestroy {
@ViewChild('lineChart') lineChart: BaseChartDirective;
@ViewChild('barChart') barChart: BaseChartDirective;

private _unsubscribeAll: Subject<any> = new Subject<any>();

public TicketLineChartData: ChartData<"line"> = {
labels: [],
datasets: [],
};

public TicketBarChartData: ChartData<"bar"> = {
labels: [],
datasets: [],
};

constructor(
private _changeDetectorRef: ChangeDetectorRef,
private _kafkaAnalyticsService: KafkaAnalyticsService,
private _userService: UserService
) {}

ngOnInit(): void {
this._kafkaAnalyticsService.kafkaTickets$
.pipe(takeUntil(this._unsubscribeAll))
.subscribe((response) => {
if (response) {
this.updateCharts(response);
// Ensure Angular detects changes
this._changeDetectorRef.markForCheck();
}
});
}

ngOnDestroy(): void {
this._unsubscribeAll.next(null);
this._unsubscribeAll.complete();
}

updateCharts(response): void {
// Process response and update chart data
// ...

if (this.lineChart) {
console.log('Updating line chart');
this.lineChart.update();
} else {
console.log('Line chart is not available');
}

if (this.barChart) {
console.log('Updating bar chart');
this.barChart.update();
} else {
console.log('Bar chart is not available');
}
}

getTicketsTime(time): void {
// Logic to get tickets based on time
// ...
this._kafkaAnalyticsService.updateTickets(startDate, endDate)
.pipe(takeUntil(this._unsubscribeAll))
.subscribe();
}
}
</code></pre>
<p>The HTML Template:</p>





<pre><code> Kafka Tickets ({{time}})


</div>
<div class="text-secondary font-medium">Trend of Kafka tickets opened</div>
</div>

<div class="mt-3 sm:mt-0 sm:ml-2">
<button class="justify-items-end" mat-flat-button [color]="'primary'" [disabled]="isLoading"
[matTooltip]="'Submit'" [matMenuTriggerFor]="timeMenu">
Select Time
</button>
<mat-menu #timeMenu="matMenu">
<button mat-menu-item *ngFor="let time of date_selection" [value]="time"
(click)="getTicketsTime(time)">
{{ time }}
</button>
</mat-menu>
</div>
</div>
<div class="flex flex-col flex-auto mt-6">
<canvas baseChart class="lineChart" [data]="TicketLineChartData" [type]="lineChartType"></canvas>
</div>
<div class="flex flex-col flex-auto mt-6">
<canvas baseChart class="barChart" [data]="TicketBarChartData" [type]="barChartType"> </canvas>
</div>
</div>
</ng-template>
</code></pre>
<p>The charts when initially loading onto the page are perfect, but when selecting a new time, they do not update unless going to the console.</p>
 

Latest posts

Online statistics

Members online
0
Guests online
3
Total visitors
3
Top