typescript Canvasjs-chart in angular双向装订

ruyhziif  于 2023-05-23  发布在  TypeScript
关注(0)|答案(2)|浏览(116)

我在angular中使用canvasjs-chart来绘制图表。(我是Angular新手)这里是我的组件ts代码:

import { Component } from '@angular/core';
import { NgModule } from '@angular/core';
@Component({
  selector: 'app-counter-component',
  templateUrl: './counter.component.html'
})
export class CounterComponent {
  public books = [{
    title: "Life is good",
    author: "benny",
    category: "life"
  }, {
    title: 'Canned in',
    author: "francis",
    category: "style"
  }];
  chartOptions = {
    title: {
      text: "Basic Column Chart in Angular"
    },
    data: [{
      type: "line",
      dataPoints: [
        { label: "Apple", y: 121 },
        { label: "Orange", y: 15 },
        { label: "Banana", y: 25 },
        { label: "Mango", y: 30 },
        { label: "Grape", y: 28 }
      ]
    }]

  };
  public changeChartData() {
    this.chartOptions.data[0].dataPoints[0].y =20;
  }

正如你所看到的,我有一个books对象,它传递给了html:

<button class="btn btn-primary" (click)="changeChartData()">change chart Data</button>
<canvasjs-chart [options]="chartOptions"></canvasjs-chart>

数据显示正确,但我的问题是当我点击change chart Data更改books对象的值时,我看不到图表中的变化。我认为问题是图表没有绑定到books对象

2ic8powd

2ic8powd1#

docs中,我看到你需要在每次选项/数据更新后调用chart.render()

public changeChartData() {
   this.chartOptions.data[0].dataPoints[0].y =20;
   this.chart.render();
}

如何在Angular中获取图表对象,请参见canvas-chart angular integration tutorialexample

  • 在组件类中声明chart: any属性
  • 添加一个方法来初始化chart属性
getChartInstance(chart: object) {
       this.chart = chart;
   }
  • 在html中包含回调:
<canvasjs-chart [options]="chartOptions" (chartInstance)="getChartInstance($event)"></canvasjs-chart>
dsekswqp

dsekswqp2#

你取决于canvasjs-chart是如何设置的。但是库在其组件中使用changeDetection.onPush策略是很正常的。这意味着它只会在输入改变和输出触发时更新,现在如果它使用onpush策略运行,对象上的变化不会被算作输入改变。因此,您可以做的是,您需要将更改设置为一个新对象。

public changeChartData() {
    this.chartOptions ={
    title: {
      text: "Basic Column Chart in Angular"
    },
    data: [{
      type: "line",
      dataPoints: [
        { label: "Apple", y: 20 },
        { label: "Orange", y: 15 },
        { label: "Banana", y: 25 },
        { label: "Mango", y: 30 },
        { label: "Grape", y: 28 }
      ]
    }]

  };
}

你所做的,是一个方向的结合。Angular 绑定中的双向绑定看起来像[(value)],其中双向绑定包含在@Input绑定[]和@Output绑定()

相关问题