Blazor Preload Service
Use Blazor Bootstrap preload service to show and hide a loading overlay from anywhere in your app. The examples below show and hide it from code and set it up for the whole app.
Use Blazor PreloadService to show and hide a loading overlay from anywhere in your app.
How it works #
PreloadService shows the Preload overlay placed in your layout while work runs, then hides it.
How to use:
- Inject
PreloadServicein the page or component that starts the work. - Call
Show()before the work starts. Pass aSpinnerColorand a loading text to change how the overlay looks. - Call
Hide()in afinallyblock, so the overlay closes even when the work fails.
<div class="d-flex flex-wrap gap-2">
<Button Color="ButtonColor.Primary" @onclick="ShowAsync">Show for 2 seconds</Button>
<Button Color="ButtonColor.Secondary" @onclick="ShowWithLoadingTextAsync">Show with loading text</Button>
<Button Color="ButtonColor.Dark" @onclick="ShowWithPrimarySpinnerAsync">Show with a primary spinner</Button>
</div>
@code {
[Inject] PreloadService PreloadService { get; set; } = default!;
private async Task ShowAsync()
{
try
{
PreloadService.Show();
await Task.Delay(2000); // call the service/api
}
finally
{
PreloadService.Hide();
}
}
private async Task ShowWithLoadingTextAsync()
{
try
{
PreloadService.Show(SpinnerColor.Light, "Loading orders...");
await Task.Delay(2000); // call the service/api
}
finally
{
PreloadService.Hide();
}
}
private async Task ShowWithPrimarySpinnerAsync()
{
try
{
PreloadService.Show(SpinnerColor.Primary);
await Task.Delay(2000); // call the service/api
}
finally
{
PreloadService.Hide();
}
}
}How to setup #
1. Add the
Preload component in MainLayout.razor page as shown below.@using BlazorBootstrap
.
.
... MainLayout.razor code goes here ...
.
.
<Preload LoadingText="Loading..." />2. Inject
PreloadService, then call the Show() and Hide() methods as shown below.@code {
[Inject] protected PreloadService PreloadService { get; set; } = default!;
private void GetEmployees()
{
try
{
PreloadService.Show();
// call the service/api to get the employees
}
catch
{
// handle exception
}
finally
{
PreloadService.Hide();
}
}
}