Issue with displaying Angular chart only resolves after resizing window following routing updates

Hey there! I'm having trouble getting my chart to show up after adding routing to my 3 tabs. Previously, without routing, everything worked fine. Now, the graph only appears after resizing the window. The chart is using PrimeNG chart with the Chart.js library. You can find more information about it here.

Here's the TypeScript code for the chart:

export class ChartComponent implements OnInit, OnDestroy {
  showError: string;
  basicData: { labels: string[]; datasets: Dataset[] } = {
    labels: [],
    datasets: [],
  };
  private componentDestroyed$: Subject<boolean> = new Subject();
  weatherDataLoading: boolean;

  constructor(
    private weatherService: WeatherService,
    public datePipe: DatePipe
  ) {}

  // ngOnInit(), ngOnDestroy(), and subscribing to data...

}

And here's the HTML code for the chart:

<div  class="card">
  <div *ngIf="weatherDataLoading" class="load-container">
    <div class="load-speeding-wheel"></div>
  </div>
  <p-chart type="line" height="80vh" [data]="basicData"></p-chart>
</div>

Additionally, here's a snippet of the service function:

// getWeatherDataForChart() implementation...

Answer №1

Angular components and variables are initialized, tracking changes for those variables with deep equality. When using arrays, they share the same memory location, which does not trigger a change in the same cycle.

During the change detection cycle, let's say it is initialized with empty values

basicData: { labels: string[]; datasets: Dataset[] } = {
    labels: [],
    datasets: [],
  };

ngOnInit essentially adds this data without triggering Angular's change detection.

To trigger this detection, simply create a new array or assign a new memory to those variables somehow.

Try this within your subscriptions, once you receive the value.

      const labels = data.labels.map((time) =>
        this.datePipe.transform(time, 'shortTime')
      );
      this.basicData = {labels: [...labels], dataset:[...data.datasets]}

This is why it worked when you did this within the subscription.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What's the best way to retrieve the quantity of each item through v-for in Vue?

In my Vue code snippet below: var itembox = new Vue({ el: '#itembox', data: { items: { cookiesncreme: { name: "Cookies N Cream", description: "description" }, ch ...

Troubleshooting Next.js 13: Issues with Error and Not Found Pages Rendering Incorrectly

I am currently working on a project with the latest version of Next.js, specifically Next.js 13, and I have organized my app directory structure accordingly. Within the app/sample directory, I have implemented custom error handling by creating pages named ...

What is the best way to invoke a class function within a static object?

Here's an example for you: export class MyClass { myString: string; constructor(s: string) { this.myString = s; } myFunction() { return "hello " + this.myString; } } export class MainComponent { static object1: MyClass = JSON. ...

Tips for styling the selected or clicked cell of an HTML5 table

Currently, I am working on a web development project to enhance my skills. I am looking to incorporate a feature that changes the color of a clicked cell to a specific color. For a demonstration, you can view this link: https://jsfiddle.net/pz6tc3ae/30/ T ...

Error Encountered in Selenium WebDriver Javascript: Unable to locate variable: $

My goal was to utilize Selenium Webdriver to click a button on a web page. I was able to successfully achieve this using Chrome Developer Tools, however, I encountered a "can't find variable" error when executing Javascript code: IJavaScriptExecutor ...

When extracting information from a table within a Vue.js and Vuetify.js function

When trying to display a table, only one row is being printed. How can I resolve this issue? I have attempted various solutions (Vanilla JS worked). This project is for educational purposes and I am relatively new to JS and Vue.js. <template> < ...

The function `map` cannot be applied to `this.state.[object]`

It seems like I might be overlooking a simple mistake, but I keep encountering this.state.iata.map is not a function , even though I have bound the context to all functions where I need to access that state. Additionally, the iata state is an array, s ...

How to create buttons in React to increase and decrease a value?

Just starting out with React and attempting to create a ticket counter. The goal is to increase or decrease by 1 based on the direction of the arrow clicked. However, I'm facing an issue where nothing is displaying on my webpage. Any ideas on what mig ...

Issue Encountered with @Input() in TypeScript

I'm currently working on developing an app with Angular 4 and encountered an error message when using @Input('inputProducts') products: Product[]; The specific error I received reads: [tslint] In the class "ProductListComponent", the di ...

Ways to eliminate toggle event in Angular

I've been doing a lot of research online, but all the solutions I find are using jquery. I'm still getting the hang of Angular and Typescript. I found this and this to be unhelpful. I built a monthpicker from scratch, which has a simple and clear ...

Retrieving data with JQuery when encountering an XHR error

When I send a jQuery AJAX request and receive a successful response, I am able to retrieve my JSON data. However, if the response code is anything other than 200, I am unable to access the data in the jQuery callback function. This data is crucial as it co ...

Increase the Step Size of an HTML Number Input by Holding Down the Time

Is there a way to implement increasing increment/step size for number inputs in HTML based on how long the user holds the stepper arrows? For instance, starting at step size=1 and gradually ramping up to larger increments like 5, 10, 20, etc. after holdin ...

Uncovering the inherent worth of an item pulled from a remote location using Vue.js

Currently, I am retrieving a list of countries by making an API call in VueX. The fetched data is then stored in a state using a mutation. Essentially, the countries are saved in a variable known as this.$state.getters.countryList, which can be accessed f ...

In React, ensure a component's state is preserved when the browser history changes

I recently developed a React application that features a classic layout with a left-side menu, title, footer, and main content section. The side menu includes navigation links structured using components such as <List>, <ListItem>, etc. from th ...

Unable to retrieve input using jquery selector

I am attempting to detect the click event on a checkbox. The Xpath for the element provided by firebug is as follows, starting with a table tag in my JSP (i.e. the table is within a div). /html/body/div[1]/div/div/div[2]/div/div[2]/div[1]/div/div[2]/table ...

using Angular's reactive forms to enable/disable form field

I have a straightforward reactive form, utilizing the Angular Material framework. this.firstFormGroup = this.fb.group({ builder_first_name: ['', Validators.required], builder_last_name: ['', Validators.required] ...

Encountering a CORS error in my Angular application while attempting to access a locally hosted Node Express API

I've been struggling with a CORS issue and can't seem to find a solution. My Node API application was built using Express, and the consumer is a simple Angular application. I've tried various solutions such as using CORS and including header ...

Exploring the 3D Carousel Effect with jQuery

After creating a 3D carousel using jQuery and CSS3, I am looking to enhance it with swiping support. While there are plenty of libraries available for detecting swipes, I specifically want the carousel to start rotating slowly when the user swipes slowly. ...

Checking the validity of email domains in real-time using Javascript

Is there a way to dynamically validate domains using JavaScript? I have a specific requirement which involves validating domains that are dynamically generated from user input. The goal is to match the domain with the company name selected and determine i ...

Angular is unable to start the variable_INITIALIZation process

I've created a method called get that returns data of type ProductModel. getProduct(id:number): Observable<ProductModel[]> { const url = `${'api/product/getProductById/'}/${id}`; return this.http.get<ProductModel[]>(u ...