Search results

Lazy Loading in Blazor Chart component

Lazy loading allows you to load data for chart on demand. Chart will fire the ScrollEnd event, in that we can get the minimum and maximum range of the axis, based on this, we can upload the data to chart.

   <ChartEvents OnScrollEnd="@ScrollChange"></ChartEvents>

  void ScrollChange(IScrollEventArgs e)
    {
        this.dataSource = GetRangeData(Convert.ToInt32(e.CurrentRange.Minimum), Convert.ToInt32(e.CurrentRange.Maximum));
        this.StateHasChanged();
    }
lazy-loading.razor
@using Syncfusion.Blazor.Charts


@if (dataSource != null)
{
    <SfChart Title="Lazy Loading Chart" @ref="chartObj">
        <ChartEvents OnScrollEnd="@ScrollChange"></ChartEvents>
        <ChartPrimaryXAxis>
            <ChartAxisScrollbarSettings Enable="true" PointsLength="1000"></ChartAxisScrollbarSettings>
        </ChartPrimaryXAxis>
        <ChartSeriesCollection>
            <ChartSeries DataSource="@dataSource" Fill="@color" XName="x" YName="y" Type="ChartSeriesType.Line">
            </ChartSeries>
        </ChartSeriesCollection>
    </SfChart>
}
else
{
    <p>Chart Loading</p>
}

@code {

    public SfChart chartObj;
    int count = 1;
    public string color = "blue";
    Random random = new Random();
    List<ColumnChartData> dataSource;
    protected override async Task OnInitializedAsync()
    {
        dataSource = this.GetData();
    }
    void ScrollChange(IScrollEventArgs e)
    {
        this.dataSource = GetRangeData(Convert.ToInt32(e.CurrentRange.Minimum), Convert.ToInt32(e.CurrentRange.Maximum));
        this.StateHasChanged();
    }
    List<ColumnChartData>
        GetRangeData(int min, int max)
    {
        List<ColumnChartData> data = new List<ColumnChartData>();
        for (; min <= max; min++)
        {
            data.Add(new ColumnChartData { x = min, y = random.Next(10, 100) });
        }
        return data;
    }
    public class ColumnChartData
    {
        public double x;
        public double y;
    }
    List<ColumnChartData>
        GetData()
    {
        List<ColumnChartData> data = new List<ColumnChartData>();
        for (; count <= 100; count++)
        {
            data.Add(new ColumnChartData { x = count++, y = random.Next(10, 100) });
        }
        return data;
    }
}