Let's say we want to render a link button to a page conditionally in our Blazor application. Because it would not make much sense to show this button on the page that it links to. We need a way to find out, if we currently are on this page or not.
Firstly we need to import the NavigationManager to our .razor file
@inject NavigationManager MyNavigationManager
Then within the bottom code block, we can add a boolean { get; set } that our conditional rendering will be based on.
private bool FaqPage { get; set; }
At last, we add the functionality:
// get the whole url var FullUrl = MyNavigationManager.Uri; // only takes whatever comes after the last "/" var PageUrl = FullUrl.Substring(FullUrl.LastIndexOf("/" + 1); // in our example, some links have a "#" with a string attached, to jump to a html id. so we need to clear that away var PurePageUrl = PageUrl.Split("#")[0]; if (PurePageUrl == "faq") { FaqPage = true; } else { FaqPage = false; }
Now, within the .razor HTML code above, we can conditionally render the button like this:
@if (!FaqPage) { <a href="/faq">FAQ Page</a> }