Introduction
Are you tired of wandering and navigating through your Blazor app like a lost tourist? Fear not; in this article, we'll explore NavigationManager in Blazor, which provides a simple and efficient way to navigate to different components and web pages. We'll cover the basics of navigating to a URL and then dive into more advanced features, such as navigating to a component, reloading the page, and replacing the current URL in the browser's history. By the end of this article, you'll have a solid understanding of how to use NavigationManager in your Blazor app.
What is navigation anyway?
Navigation is the process of moving between different pages or parts of a website. It can be achieved by using links, buttons, or other UI elements to redirect users to different sections of the website. Navigation is a fundamental part of the user experience, allowing users to quickly and easily find the information or functionality they need.
What is NavigationManager?
NavigationManager is a service in Blazor that provides a way to navigate between pages within a Blazor application. It uses the browser's history API to track the user's navigation history and allows you to navigate between pages using relative or absolute URLs.
To use NavigationManager, you must first inject it into your component or service. You can do this by using the @inject directive.
@inject NavigationManager NavigationManager;
- Relative URL: A relative URL is relative to the current page's URL. For example, if the current page's URL is https://www.mywebsite.com/, then to navigate to the about page of this website, you just need "../about" This will redirect you to https://www.mywebsite.com/about.
// Navigate to a relative URL NavigationManager.NavigateTo("/about"); - Absolute URL: This is a complete URL that includes the protocol, domain, and path. For example, to reach about page from the previous example, you need the complete URL https://www.mywebsite.com/about.
// Navigate to an absolute URL NavigationManager.NavigateTo("https://www.mywebsite.com/about");
Class NavigationManager is packed with lots of features. However, we are interested in the following property, event, and methods.
- Uri: A property that gets or sets the current URI. Always represented as an absolute URI in string form.
// Get the current URI string uri = NavigationManager.Uri; // Set the current URI NavigationManager.Uri = "/about"; - LocationChanged: An event that fires when the navigation location has changed.
protected override void OnInitialized() { //Subscribing to an event NavigationManager.LocationChanged += OnLocationChanged; } private void OnLocationChanged(object sender, LocationChangedEventArgs e) { // Do something }



Join the conversation! Your thoughts help the community grow.