【问题标题】:how to use chartjs graph in a *ngFor loop如何在 *ngFor 循环中使用 chartjs 图形
【发布时间】:2022-01-04 14:14:07
【问题描述】:

我在尝试为 *ngFor 循环中的每个 mat-card 创建图表时遇到了挑战。我正在这样设置画布:

 <canvas id="coinLineChart{{coin_index}}" width="200" height="150"></canvas> 

然后像这样创建一个 id 值的变量:

 let chart_id = `coinLineChart` + `${this.coin_index}`.

然后我尝试像这样获取 ctx 值:

 coinLineChart = document.getElementById(chart_id);
 const ctx = coinLineChart.getContext("2d"); 

但 coinlLineChart 结果为空。谁能建议一种方法来做到这一点?我正在使用带有 Angular 13 的 chartjs v3

【问题讨论】:

    标签: css angular chart.js


    【解决方案1】:

    您可以使用 viewChildren 或 viewChild 链接到画布标签,以列出循环侧的所有画布

    在 html 中:

    <canvas #canvas width="200" height="150"></canvas> 
    

    如果你的组件直接有 *ngFor 和 canvas 元素,你有两种情况

    在控制器中

    @ViewChildren('canvas') canvasList: QueryList<ElementRef>
    

    在你需要操作画布的函数中

     this.canvasList.toArray().forEach(canvas => {
        const ctx = canvas.getContext("2d");
        //other code on one canvas
    });
    

    如果您的画布位于子组件内,您可以使用 ViewChild 指令来操作它

    在子控制器中

    @ViewChild('canvas') canvas: ElementRef
    

    在你需要操作画布的子函数中

        const ctx = this.canvas.getContext("2d");
        //other code on one canvas
    

    【讨论】:

    • 这很有趣....但我不明白它是如何工作的?您会看到我的循环 (*ngFor) 在我的父母身上,他多次调用 。那么孩子内部的另一个循环如何工作?因为每次访问孩子时,我只有一组数据和该数据的索引。
    • 好的,如果画布在子组件中,您还可以使用元素 viewChild 来引用控制器中的 html 组件@ViewChild('canvas') canvas: ElementRef
    • 这个想法是不必做一个 document.get{Seletcor} 但可以访问控制器端的 html 标签
    • 我给你发了一个链接到另一个有趣的 stackoverflow 帖子,非常接近你的情况stackoverflow.com/questions/34636435/…
    • 我会及时更新我的​​回复
    猜你喜欢
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    相关资源
    最近更新 更多