Home > Software engineering >  Dynamically add a chart component to a Razor Page
Dynamically add a chart component to a Razor Page

Time:06-18

I have build a nice chart (serverside) component with blazor. It uses jschart. Everything is fine, and it works great.

Inside the ChartComponent. I have this.

@using Blazorise.Charts
<Div Style=@($"position: relative; height:{ViewHeight}vh; width:{ViewWidth}vw;")>
    <LineChart @ref="lineChart" TItem="double" Clicked="@OnClicked"  Options="@chartOptions"/>
</Div>

(note the lineChart reference) and in the Razor.cs file I have defined a lineChart variable as well (used as Ref in Razor Page)

 LineChart<double> lineChart;

The problem is when I place it on a page without the foreach everything works fine.

<ChartComponent ViewHeight=50 ViewWidth=80 ColorScheme="Classic20" Multiple=true Items=@items></ChartComponent>

But now I want to add multiple of those components to the page.

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

But when I put it inside a foreach I get an error stating lineChart is null... I have tried several things but my guess is I am missing something.

inside the chartcomponent I do

await lineChart.Clear();

which gives me a

Object reference not set to an instance of an object.

Tried several things but don't know how to solve it.

I tried the solution proposed by MetinYakar.NET but I still get the same result.

DebugView

The chartcomponent is not null but some variables inside the chart component are.

Seems like when the component is on the page during the first render it wil work, but when it's not on the page during the first render the component is not properly initialized, a render of the chart itself willl fail.

CodePudding user response:

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>
}

CodePudding user response:

It won't hurt to put an @key in there:

 <ChartComponent @key="graphSelector" ... 
  • Related