Dipin raman
Dipin raman

Reputation: 183

Angular 4:PrimeNg DoughnutChart dynamic data issue.

I have recently been working on primeng charts, and I am using DoughnutChart provided by PrimeNG. I want to pass a number value stored in a variable as data in the ts file for this chart, but it will not show anything in the UI,where as if data is static it works absolutely fine.This is the code for the same:

1.)Working one:-

this.invoicedata = {
            labels: ['InvoiceQty', 'TotalQty'],
            datasets: [
                {
                    data: [50, 50],
                    backgroundColor: [
                        "#ff9800",
                        "#ffffff",

                    ],
                    hoverBackgroundColor: [
                        "#ff9800",
                        "#ffffff",

                    ]
                }]
        }

2.)Non-working one:-

  this.invoicedata = {
                labels: ['InvoiceQty', 'TotalQty'],
                datasets: [
                    {
                        data: [this.pICompletionPercentage, this.PIPendingpercent],
                        backgroundColor: [
                            "#ff9800",
                            "#ffffff",

                        ],
                        hoverBackgroundColor: [
                            "#ff9800",
                            "#ffffff",

                        ]
                    }]
            }

This is HTML for the same:-

 <div class="row">
                                <p-chart type="doughnut" [data]="invoicedata" width="150px"></p-chart>
                                <p class="text-center">Invoiced- {{pICompletionPercentage}}%</p>
                            </div>

Upvotes: 2

Views: 2382

Answers (1)

Bunyamin Coskuner
Bunyamin Coskuner

Reputation: 8859

The problem is probably that you set your invoiceData before your service call is finished. Since, you will have to wait for a while to populate invoiceData, you may want to delay primeng chart initialization too. You can achieve this with *ngIf.

So, you can do something like this

Your.component.ts

 @Component({
     selector: 'your-comp',
     template: `
         <p-chart *ngIf="invoiceData" type="doughnut" [data]="invoiceData">
         </p-chart>
     `
 })
 export class YourComponent implements OnInit {
     invoiceData;

     constructor(private someService: SomeService) {}

     ngOnInit() {
         this.getData();
     }

     getData() {
         this.someService
             .getData()
             .subscribe(resp => {
                 // here you can set your data the way you want.
                 this.invoiceData = resp;
             })
     }

 }

Upvotes: 2

Related Questions