gpt4 book ai didi

javascript - chart.js 未在 angular2 (rc1) 中显示

转载 作者:行者123 更新时间:2023-12-03 17:01:10 25 4
gpt4 key购买 nike

我对 chart.js 和 angular2 有疑问。当我尝试将图表绑定(bind)到 Canvas (在 Angular 模板内)时,没有显示任何内容。在 Angular 之外一切正常。我的 StatisticComponent 包含在路由器 (router-outlet) 中。

组件:

@Component({
selector: 'statistic',
templateUrl: 'views/statistic.component.html'
})
class ChartComponent implements AfterViewInit {
@ViewChild('canvas') canvasElement;

ngAfterViewInit() {
var ctx = document.getElementById('canvas');
//var ctx = this.canvasElement.nativeElement;
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});

}
}

模板:

<h2>Statistic</h2>
<canvas #canvas id="canvas"></canvas>

当我设置超时并引用全局 html Canvas (不在模板内)时,一切正常。

我发现了一个类似的帖子: chart does not display in angular2 component

但这并没有帮助。我不使用 systemjs 作为加载器,我使用 browserify。希望有人能帮忙。

//更新

//这个可行//追加新元素

class ChartComponent implements AfterViewInit {
@ViewChild('container') containerElement;

ngAfterViewInit() {
var canvas = document.createElement('canvas');
this.containerElement.nativeElement.appendChild(canvas);

var myChart = new Chart(canvas, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
}

//这行不通 - 为什么?//直接使用VIECHHILD

class ChartComponent implements AfterViewInit {
@ViewChild('canvas') canvas;

ngAfterViewInit() {
var myChart = new Chart(this.canvas.nativeElement, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
}

最佳答案

尝试更新您的模板并将您的 Canvas 元素包装在一个 div 中。不知道原因,但当 Canvas 元素位于模板 html 的根部时,问题似乎出现了。

更新的模板:

<h2>Statistic</h2>
<div>
<canvas #canvas id="canvas"></canvas>
</div>

关于javascript - chart.js 未在 angular2 (rc1) 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37392232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com