Blazor conditional component attributes

Blazor conditional component attributes

Adding Attributes to Blazor component conditionally.

I wanted to add the href element on the NavLink component based on some condition in my code.

This was required in my case since if you add an href attribute to a NavLink, it automatically starts adding the .active class to the NavLink when the current route is empty "/", hence highlighting any NavLink in my menu which did not want to add an href.

I was able to achieve this with a Helper Method:

  • Create a helper method that returns the appropriate NavLink attributes based on your condition.

  • Example:

  • HasLink below can be replaced with your condition based on which you need to add the href (or any other) attribute.

@code {
    private bool HasLink => !string.IsNullOrWhiteSpace(MyModel.Link);

    private Dictionary<string, object> GetNavLinkAttributes()
    {
        var attributes = new Dictionary<string, object>();
        if (HasLink)
        {
            attributes["href"] = MyModel.Link;
            attributes["Match"] = NavLinkMatch.All;
        }
        return attributes;
    }
}

<NavLink @attributes="GetNavLinkAttributes()">Visit the website</NavLink>

This approach keeps your component code cleaner by separating the attribute logic in the GetNavLinkAttributes method.