Search code examples
chart.jsblazorblazor-webassemblyasp.net-blazor

How to use chart.js in blazor?


I am trying to follow this example from mariusmuntean/ChartJs.Blazor :

https://github.com/mariusmuntean/ChartJs.Blazor

The code runs but I am getting this error:

InvalidOperationException: Object of type 'Project.Shared.Chart' does not have a property matching the name '@Config'.

@page "/charts/bar/horizontal"
@using ChartJs.Blazor.PieChart
@using System.Drawing
@* @layout SampleLayout *@
@using ChartJs.Blazor.Util
@using ChartJs.Blazor.Common
@using ChartJs.Blazor.Common.Axes
@using ChartJs.Blazor.Common.Axes.Ticks
@using ChartJs.Blazor.Common.Enums
@using ChartJs.Blazor.Common.Handlers
@using ChartJs.Blazor.Common.Time
@using ChartJs.Blazor.Interop

<Chart Config="_config"></Chart>

@code {


private PieConfig _config;

protected override void OnInitialized()
{
    _config = new PieConfig
    {
        Options = new PieOptions
        {
            Responsive = true,
            Title = new OptionsTitle
            {
                Display = true,
                Text = "ChartJs.Blazor Pie Chart"
            }
        }
    };

    foreach (string color in new[] { "Red", "Yellow", "Green", "Blue" })
    {
        _config.Data.Labels.Add(color);
    }

    PieDataset<int> dataset = new PieDataset<int>(new[] { 6, 5, 3, 7 })
    {
        BackgroundColor = new[]
        {
            ColorUtil.ColorHexString(255, 99, 132), // Slice 1 aka "Red"
            ColorUtil.ColorHexString(255, 205, 86), // Slice 2 aka "Yellow"
            ColorUtil.ColorHexString(75, 192, 192), // Slice 3 aka "Green"
            ColorUtil.ColorHexString(54, 162, 235), // Slice 4 aka "Blue"
        }
    };

    _config.Data.Datasets.Add(dataset);
}
}

Solution

  • After several trials I came to a fact that it should be written this way:

    <ChartJs.Blazor.Chart Config="_config"></ChartJs.Blazor.Chart>
    

    Instead of:

    <Chart Config="_config"></Chart>