blazor passing data between components code example

Example 1: how to pass property between blazor components

@page "/"
@inject Services.AppData AppData

<h1>First Page</h1>
<input type="number" @bind="AppData.Age" />
<br>
<a href="/page2">Go to Page 2</a>

Example 2: how to pass property between blazor components

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<Services.AppData>();
}

Example 3: how to pass property between blazor components

@inject Services.AppData AppData
<h3>Input Component</h3>
<input type="number" @bind="AppData.Number" />
<br /><br />
<select @bind="AppData.Color">
    <option value="#add8e6">Light Blue</option>
    <option value="#90ee90">Light Green</option>
    <option value="#d3d3d3">Light Grey</option>
    <option value="#ffb6c1">Light Pink</option>
    <option value="#fff">White</option>
</select>
<br /><br />

Example 4: how to pass property between blazor components

@page "/"
@using AppDataService.Components
@inject Services.AppData AppData

<h1>Blazor Singleton Test</h1>
<InputComponent />
<DisplayComponent />
<a href="/page2">Go to Page 2</a>

@code {
    protected override void OnInitialized()
    {
        AppData.OnChange += MyEventHandler;
    }

    private void MyEventHandler()
    {
        Console.WriteLine("AppData changed.");
    }
}

Example 5: how to pass property between blazor components

services.AddScoped<Services.AppData>();

Tags:

Misc Example