Blazor lets you build reusable components to encapsulate common behaviors. A common need is showing a loading indicator while fetching data from a database or a remote service, processing a form, or handling any other long-running operation.
This Loading component is simple to create but highly useful!
Razor
@if (IsLoading)
{
if (LoadingTemplate != null)
{
@LoadingTemplate
}
else
{
<div class="spinner-border"></div>
<span style="display: inline-block; vertical-align: super">@LoadingText</span>
}
}
else
{
@ChildContent
}
@code{
[Parameter]
public bool IsLoading { get; set; }
[Parameter]
public string LoadingText { get; set; } = "Loading...";
[Parameter]
public RenderFragment LoadingTemplate { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
}
Use the component to display a loading indicator while data is being fetched:
Razor
@page "/"
<Loading IsLoading="customers is null">
<ul>
@foreach (var customer in customers)
{
<li>@customer.Name</li>
}
</ul>
</Loading>
@code {
private List<Customer> customers;
protected override async Task OnInitializedAsync()
{
await Task.Delay(1000); // simulate loading
customers = new List<Customer>();
}
}
You can also use it to indicate that an action is in progress:
Razor
@page "/"
<button type=button @onclick="ProcessAsync">Process</button>
<Loading IsLoading="isProcessing">
Please wait, while we work our Magic 🦄
</Loading>
@code {
bool isProcessing;
Task ProcessAsync()
{
isProcessing = true;
try
{
await Task.Delay(1000); // simulate loading
}
finally
{
isProcessing = false;
}
}
}
Do you have a question or a suggestion about this post? Contact me!