首页 > 解决方案 > 将一个变量传递给另一个变量

问题描述

我正在创建一个从变量生成的饼图public pieChartData:number[] = [300, this.Goal]。我正在尝试for使用对象数组上的循环在构造函数中获取正确的数据

  data = [{
    Id: 1,
    YTDGoal: 125000
  }]

但是当传入pieChartData,时this.Goal是未定义的。

我该如何解决这个问题?

为这个问题创建了一个 Stackblitz

标签: angular

解决方案


尝试这个。

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  data = [{
    Id: 1,
    YTDGoal: 125000
  }]

  Goal;
  public pieChartLabels:string[] = ['Download Sales', 'YTD Goal'];
  public pieChartData:number[] = [300, this.Goal];
  public pieChartType:string = 'pie';
  public pieChartCustomColors = [{
    backgroundColor: ['blue', 'red']
  }]

  constructor() {
    for (let i = 0; i < this.data.length; i++) {
      this.Goal = this.data[i].YTDGoal
    }
    this. pieChartData = [300, this.Goal];
  }

  public chartClicked(e:any):void {
    console.log(e);
  }

  public chartHovered(e:any):void {
    console.log(e);
  }

}

推荐阅读