Skip to content

Defaults and Helpers

ipax77 edited this page May 22, 2026 · 1 revision

Defaults and Helpers

Some chart behavior belongs at app setup level, while other tasks belong to the rendered ChartComponent. These APIs reduce repeated chart configuration and cover UI actions that need an actual chart instance.

App-wide defaults

AddChartJs(...) can map shared values to Chart.defaults before the first chart is constructed:

builder.Services.AddChartJs(options =>
{
    options.ChartJsCallbacksModuleLocation =
        $"{builder.HostEnvironment.BaseAddress}_content/my-app/chartJsCallbacks.js";

    options.Defaults = new ChartJsDefaultsOptions
    {
        Color = "#1f2937",
        BorderColor = "#d1d5db",
        Font = new Font
        {
            Family = "Inter, system-ui, sans-serif",
            Size = 12
        },
        Datasets = new ChartJsOptionsDatasets
        {
            Bar = new { barPercentage = 0.8 },
            Line = new { tension = 0.25 }
        },
        OnClick = ChartJsFunction.FromName("globalChartClick")
    };
});

Per-chart ChartJsConfig.Options still override shared defaults where a chart needs a different setting.

Keep a component reference

Helpers operate on a rendered chart, so Razor keeps a ChartComponent reference:

<ChartComponent @ref="chartComponent" ChartJsConfig="chartJsConfig" />

Resize and export

private ChartComponent? chartComponent;
private string? imageDataUrl;

private async Task ResizeChart()
{
    if (chartComponent is not null)
    {
        await chartComponent.ResizeChart(640, 360);
    }
}

private async Task MakeImage()
{
    if (chartComponent is not null)
    {
        imageDataUrl = await chartComponent.GetChartImage();
    }
}

GetChartImage(...) returns image data from the chart canvas. Optional arguments let callers select image type, quality, width, and height.

Visibility and legend helpers

The component also exposes chart-instance actions used by legends and interactive UI:

  • SetDatasetVisibility(...)
  • ShowDataset(...) and HideDataset(...)
  • ToggleDataVisibility(...) for pie and doughnut item visibility
  • GetLegendItems()
  • SetDatasetPointsActive(...)

The Events and HTML Legends page shows these legend-oriented helpers in a full Blazor flow.

Sample source

Clone this wiki locally