Your Blazor application may require some initialization steps. For instance, you may need to get the user data from a web API before the user can use the application. Depending on the network this can be fast or take a few seconds. You may want to show a loading screen while initializing the application.
The solution to everything in Blazor is to create a component! In this case, the component will load the data asynchronously and display a loading message meanwhile. Once the data is loaded, it replaces the loading message by the actual content. So, if you wrap the main component (surely the Router
) by this loading component, the user will see the loading message until the application is ready. If you have multiple initialization steps, you can even use a progress bar to indicate the progression.
To create the component create a new file named Shared/LoadingScreen.razor
with the following content:
@if (isLoaded)
{
@ChildContent
}
else
{
<div>Loading screen...</div>
}
@code {
bool isLoaded;
[Parameter]
public RenderFragment ChildContent { get; set; }
protected override async Task OnInitializedAsync()
{
await Task.Delay(4000); // TODO actual initialization job
isLoaded = true;
}
}
The code is pretty simple. The only trick is to use RenderFragment ChildContent { get; set; }
. This parameter is a template that takes its value from the child content of the component and you can render it using @ChildContent
when needed. In this case, we display the content only when the component has finished its initialization.
#blazor #.net #asp.net core #web