[Chartjs]-Dynamically add a chart component to a Razor Page

1👍

Ok guys thanks for helping me.

I took the advice from Henk, and started from scratch with the codebase from The Blazorise Chart Example. I wrapped that like I did with my own component and to my surpise I could add multiple of those to my page.

After a lot of tracing and trying the most important change is that I moved the initialization of the chart to OnAfterRenderAsync.

    protected override async Task OnAfterRenderAsync( bool firstRender )
    {
        if ( firstRender )
        {
            await DataSetToChartSeries();
        }
    }

This made all the difference

1👍

You need to use a property value in blazor project and add first declaration. Ex;

LineChart<double> lineChart { get; set; } = new LineChart<double>();

And check null for show in the view

@if(datasets?.Count > 0){
    @foreach (string graphSelector in datasets)
    {
         <ChartComponent ViewHeight=50 ViewWidth=80 ColorScheme="Classic20" Multiple=true Items=@(items.Where(p => p.CounterInstance == graphSelector).ToList())></ChartComponent>
    }
 } else {
    <b>datasets object null or empty</b>
}

1👍

Items=@(items.Where(p => p.CounterInstance == graphSelector) looks a little suspicious to me. Is CounterInstance a string, and what is in the string graphSelector? I don’t think ANY of that sounds like it should be a string at all.

You complained that

@foreach (string graphSelector in datasets)
{
     <ChartComponent ViewHeight=50 ViewWidth=80 ColorScheme="Classic20" Multiple=true Items=@(items.Where(p => p.CounterInstance == graphSelector).ToList())></ChartComponent>
}

gives an error that lineChart is null, but there’s nothing like that in the <ChartComponent>

Leave a comment