Why is it that Chart.js fails to render in a child component, yet works perfectly in the parent component?

I attempted to create a chart in a parent component using a child component but encountered some difficulties. Here is my code:

Parent component:

@Component({
  selector: 'app-tickets',
  template: '<canvas id="newChart"></canvas>'
})
export class TicketsComponent implements OnInit {

  ngOnInit(): void {

    var chart = new Chart('newChart', {
      type: 'line',
      data: {
          labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
          datasets: 
          [
            {
              label: 'Total De Cada Mes',
              data: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
              backgroundColor: 'rgba(0, 123, 255, 0.5)',
              borderColor: 'rgba(0, 123, 155, 1)',
              borderWidth: 2
            },
            {
              label: 'Total de domicilios',
              data: [0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0],
              backgroundColor: 'rgba(12, 092, 323, 0.5)',
              borderColor: 'rgba(12, 092, 323, 1)',
              borderWidth: 2,
              hidden: true
            }
          ]
      },
      options: {
          scales: {
              yAxes: [{
                  ticks: {
                      beginAtZero: true
                  }
              }]
          }
      }
    });
  }
}

It should look like this: https://i.sstatic.net/ybTlx.png

However, when I tried to do the same thing in a child component, I encountered this issue:

Parent component:

@Component({
  selector: 'app-tickets',
  template: '<app-tickets-chart id="newChart"></app-tickets-chart>'
})
export class TicketsComponent {
}

Child Component (Using the same chart):

@Component({
  selector: 'app-tickets-chart',
  template: "<canvas [id]='chartId'></canvas>"
})
export class TicketsChartComponent implements AfterViewInit {

  @Input()
  public chartId: string;

  ngAfterViewInit(): void {
     if(this.chartId === '') {
      throw new Error("Attribute 'chartId' is required.");
    }

    var chart = new Chart(this.chartId, {
      type: 'line',
      data: {
          labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
          datasets: 
          [
            {
              label: 'Total De Cada Mes',
              data: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
              backgroundColor: 'rgba(0, 123, 255, 0.5)',
              borderColor: 'rgba(0, 123, 155, 1)',
              borderWidth: 2
            },
            {
              label: 'Total de domicilios',
              data: [0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0],
              backgroundColor: 'rgba(12, 092, 323, 0.5)',
              borderColor: 'rgba(12, 092, 323, 1)',
              borderWidth: 2,
              hidden: true
            }
          ]
      },
      options: {
          scales: {
              yAxes: [{
                  ticks: {
                      beginAtZero: true
                  }
              }]
          }
      }
    });
  }
}

And it appears like this:

https://i.sstatic.net/JT33K.png

What should I do to fix this issue?

Answer №1

I implemented these styles in the child component which successfully solved my issue.

:host {
    display: block;
    width: 100%;
    height: 100%;
}

And that's the solution!

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

The error message "Identifier 'title' is not defined. '{}' does not contain such a member angular 8" indicates that the title variable is not recognized or defined in the

Here is the code snippet of my component: import { Router, ActivatedRoute } from '@angular/router'; import { Component, OnInit } from '@angular/core'; import { CategoriesService } from 'src/app/categories.service'; import { P ...

What is the best way to transmit two distinct sets of data from a child component to the v-model of a parent component?

Currently, I am working on a project using vuejs 2 and typescript. In this project, I need to pass two different sets of data - data and attachments - within the parent component. I am utilizing vue-property-decorator for this purpose. However, I am facing ...

Error encountered when implementing Angular Model Class within an array structure

In the current project, I have developed a class and am attempting to utilize the constructor format for certain content within the project. Here is my Angular class - import { Languages } from './temp-languages.enum'; export class Snippet { ...

A guide on the dynamic implementation of loading a child component view within a parent component view in Angular

Is there a method available to insert a component into another component? For example, consider the following code: ParentComponent - ts export class ParentComponent implements { childComponentsSelector:string = "<app-child-component></app-ch ...

Experiencing an issue with Jest - Error: unable to access property 'forEach' of null

After watching some tutorials, I decided to create a sample project in Jest for writing tests. In a TypeScript file, I included a basic calculation function like this: Calc.cs export class Calc { public add(num1: number, num2: number): number { ...

Set the component variable to hold the output of an asynchronous method within a service

As I work on developing an application, I aim to keep my component code concise and devoid of unnecessary clutter. To achieve this, I plan to offload complex logic into a service which will then be injected into the component. Suppose my component includes ...

Ensure all promises are resolved inside of for loops before moving on to the next

Within my angular 11 component, I have a process that iterates through elements on a page and converts them from HTML to canvas to images, which are then appended to a form. The problem I am encountering is that the promise always resolves after the ' ...

Setting the title of a document in Angular 5 using HTML escaped characters

It seems like a simple problem, but I can't seem to find an easy solution. Currently, I am using the Title service to add titles to my documents and everything is working fine. You can check out the documentation here: https://angular.io/guide/set-doc ...

Is there a way to trigger the ngOnInit() function in Angular 2 for a second time

I need help understanding how to re-trigger the ngOnInit() function when calling another method. Can you provide guidance on this in the following code snippet? ngOnInit(): void { this.route.params.subscribe((params: Params) => { this.model = th ...

What is the process of programmatically sorting a column in a Material UI DataGrid?

Hey there! I'm currently working on a DataGrid that has a column with a custom header, specifically a Select option. My goal is to have the column sorted in descending order every time a user selects an option from the dropdown menu. renderHeader: (pa ...

Running a Jest test that triggers process.exit within an eternal setInterval loop with a latency of 0, all while utilizing Single

In the original project, there is a class that performs long-running tasks in separate processes on servers. These processes occasionally receive 'SIGINT' signals to stop, and I need to persist the state when this happens. To achieve this, I wrap ...

Is there a way to retrieve the status_code 400 in Angular?

How can I determine if the status code equals 400 in Angular to display a notification? I attempted the following method: signUp() { let body = { login: this.username, nom: this.nom, prenom: this.prenom, adress: thi ...

Navigating through pages in your IONIC 3 application: A guide to routing

I have been working on an Ionic 3 project and currently using NavController for page navigation. For example: this.navCtrl.push(DetailsPage); However, I now need to switch to Angular routing. I came across a similar query regarding Ionic 2 in this link. ...

Issue: Property is not found within the parameters of the Generic Type

Currently, I am delving into the world of Typescript and have been exploring various exercises that I stumbled upon online. However, I have encountered some trouble with the feedback on incorrect solutions. Specifically, I am facing an issue with the follo ...

Having trouble reading local storage in Angular 2

I have inserted a token into local storage and am attempting to console.log it. Here is my code snippet: ngOnInit(){ console.log('Member Info: ', JSON.parse(localStorage.getItem('LOCAL_TOKEN_KEY'))); } Although this seems correct ...

Embed the value of an array in HTML

Upon running console.log, the data output appears as follows: {TotalPendingResponseCount: 0, TotalRequestSendCount: 1, TotalRequestReceivedCount: 1, TotalRequestRejectCount: 3} To store this information, I am holding it in an array: userData : arrayResp ...

Is there a way to simultaneously filter the mat table data source and its related asynchronous properties?

Scenario: My current setup consists of angular version 9.1.7, angular-material version 9.2.3, macOS version 10.14.6, and ngrx libraries (store, data, entity) version 9.1.2 Description: I currently have a functional material table with a MatTableDataSourc ...

Adding a new element to the div by referencing its class name

One way to add a component to the view is by using ViewContainerRef. For instance, HTML File: <div #Ref>it is possible to append the component here</div> TS File: @ViewChild("Ref", { read: ViewContainerRef }) public Ref: ViewContainerRe ...

Adding an image to a React component in your project

I am currently working on an app that utilizes React and Typescript. To retrieve data, I am integrating a free API. My goal is to incorporate a default image for objects that lack images. Here is the project structure: https://i.stack.imgur.com/xfIYD.pn ...

Leveraging the power of react-hook-form in combination with the latest version 6 of @mui

When using MUI v5 date pickers, I utilized the following method to register the input with react-hook-form: <DatePicker ...date picker props renderInput={(params) => { return ( <TextField {...params} ...