New to Telerik UI for Blazor? Start a free 30-day trial
Reuse One Notification Instance in the App
Updated over 6 months ago
Environment
| Product | Notification for Blazor |
Description
This KB article answers the following questions:
- How to use a single Telerik Notification component for Blazor in multiple other Razor files?
- How to reuse one Notification instance in the whole Blazor application?
Solution
There are two possible ways to implement a reusable Notification component instance:
The Notification component in both scenarios must be defined:
- As a descendant (or child) of the
<TelerikRootComponent>. - In a
.razorfile with enabled interactive render mode. TheMainLayoutis interactive only if the Blazor app has Global interactivity location.
Pass the Notification in a Cascading Value
- Define a Telerik Notification component in
MainLayout.razor. - Set the Notification
@refattribute. Use aninternalorpublicaccessor. - Wrap the
@BodyinMainLayoutin a<CascadingValue>that passes theMainLayoutinstance itself. This avoids potential issues with missing Notification instance in child components on initial app load. SetIsFixed="true"to theCascadingValueto avoid unnecessary renders. - Consume the
MainLayoutinstance in child Razor components as a[CascadingParameter]and access the Notification instance methods through theMainLayoutinstance.
Reuse a Notification as a CascadingValue
RAZOR
@inherits LayoutComponentBase
<TelerikRootComponent>
<TelerikNotification @ref="@NotificationRef" />
<CascadingValue Value="@this" Name="MainLayoutRef" IsFixed="true">
@Body
</CascadingValue>
</TelerikRootComponent>
@code {
internal TelerikNotification? NotificationRef { get; set; }
}Use the Notification as a Service
- Implement a service that holds a Notification component instance as a property and executes component methods.
- Register the service in
Program.cs. - Define a Telerik Notification component in
MainLayout.razor. - Inject the service in
MainLayout.razorand set the Notification@refattribute to a property of the service. - Inject and use the service in other Razor components.
Reuse a Notification in a service
C#
using Telerik.Blazor.Components;
namespace YourAppName.Services
{
public class NotificationService
{
public TelerikNotification? NotificationRef { get; set; }
public void Show(string text, string? themeColor = null)
{
NotificationRef?.Show(new NotificationModel()
{
Text = text,
ThemeColor = themeColor
});
}
public void Show(NotificationModel notificationModel)
{
NotificationRef?.Show(notificationModel);
}
public void HideAll()
{
NotificationRef?.HideAll();
}
}
}