角度-将对象更改为数组,并使其在更改时侦听

时间:2019-06-17 15:29:31

标签: angular typescript chart.js angular-components

我知道这个问题非常基本,但是在以下情况下我需要帮助。 首先,我想在单个数组中使用Fix接口的平衡值,将其添加到chart.js数据中,并将名称值添加到标签中。

我已经构建了界面和组件。

您可以看到(并且我看到您将头砸在墙上),我在两行(labels: ....data: ....)中做了一个for循环,显示了我的期望。

export interface Fix {
  name?: String,
  balance?: number
}

import { Component, OnInit } from '@angular/core';
import { Chart } from 'chart.js';
import { Fix } from '../fix';

@Component({
  selector: 'app-container',
  templateUrl: './container.component.html',
  styleUrls: ['./container.component.scss']
})
export class ContainerComponent implements OnInit {

  public chart: Chart;
  public fix: Fix[];

  constructor() {

    this.fix = [
      {'name': 'Fix1', 'balance': 123},
      {'name': 'Fix2', 'balance': 23}
    ]

  }

  ngOnInit() {
    this.chart = new Chart('chart', {
        type: 'doughnut',
        data: {
            labels: [for (let bal of this.fix) {bal.name}],
            datasets: [{
                label: '# of Votes',
                data: [for (let bal of this.fix) {bal.balance}]
            }]
        }
    });
  }

}

我知道我可以像这样运行循环

for (let x if this.fix) {
    labelsArray.push(x.name);
    fixArray.push(x.balance);
}

并将其用于我的chart.js,但这将我带到了下一点。 稍后,将在子组件中输出对象,而不是在构造函数中定义fix。每次值更改时,图表都应更新。

1 个答案:

答案 0 :(得分:0)

不确定我是否会100%关注您,但这是我可以看到的您要求的内容:

// return only the id values in your objects
console.log(this.fix.map(x=>x.id));

为了强制在子组件中进行更新,我这样做:

ParentComponent视图

<child-component [fix]="childFixArray"></child-component>

ChildComponent控制器

// This property is bound using its original name.
@Input('childFixArray') fix: [];

// sometimes updates will not occur fi ANgular is not triggered to update the DOM. 
// Use ngOnChanges in the child to monitor for updates
ngOnChanges(changes: SimpleChanges) {
    if ('fix' in changes) {
        // console.log(this.fix);
    }
    this.doSomething(changes.fix.currentValue);
    this.doSomething(changes.fix.previousValue);
    this.doSomething(changes.fix.firstChange);
}