我正在使用NodeJS,Angular2和ng2-chartjs2。下面我列出了我的代码的相关部分,即渲染图表。使用固定日期范围从API将数据加载到this.data中。我想允许用户选择日期范围,然后更新图表。从here我知道你可以在图表对象上调用update()来更新其中的数据,但我不知道如何获取图表对象,因为组件代码实际上从未有过引用它 - 它在渲染模板时自动完成。查看source code(第13行),我看到作者打算使该对象可用。我联系了作者,但还没有收到回复,需要动起来。我已经学到了很多关于Angular2的知识,但我还不是专家,所以也许对Angular2的深入理解使这一点变得明显。我怎样才能访问对象以调用update(),或者以其他方式干净?
模板包含
<chart [options]="simple.options"></chart>
,组件打字稿代码包含
import { ChartComponent } from 'ng2-chartjs2';
...
@Component({
selector: 'home',
templateUrl: 'client/components/home/home.component.html',
styleUrls: ['client/components/home/home.component.css'],
directives: [DashboardLayoutComponent, CORE_DIRECTIVES, ChartComponent],
pipes: [AddCommasPipe],
})
...
setCurrentSimpleChart = (simpleType: number): void => {
this.simple.options = {
type: 'line',
options: this.globalOptions,
data: {
labels: this.data[simpleType].labels,
datasets: [{
label: this.titles[simpleType],
data: this.data[simpleType].data,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1
}],
},
};
...
}
更新:如果这有助于任何人:我实际上在页面上有两个不同的图表,所以我根据接受的答案搜索并找到ViewChildren,并将它们映射到不同的变量,以便我可以单独更新它们,用< / p>
[this.simpleChart, this.liftChart] = this.chartComponents.toArray().map(component => component.chart);
(另请注意,这是使用了一个角度为2的rc - 因为那时指令等已经移出了组件本身。)
答案 0 :(得分:2)
您可以使用char16_t
:
ViewChild
然后你可以获得@ViewChild(ChartComponent) chartComp;
对象:
chart