diff --git a/src/Microsoft.AspNetCore.Blazor/Routing/NavLink.cs b/src/Microsoft.AspNetCore.Blazor/Routing/NavLink.cs index 8277f076f5..ce9bbe8ffa 100644 --- a/src/Microsoft.AspNetCore.Blazor/Routing/NavLink.cs +++ b/src/Microsoft.AspNetCore.Blazor/Routing/NavLink.cs @@ -32,6 +32,12 @@ namespace Microsoft.AspNetCore.Blazor.Routing private string _hrefAbsolute; private IReadOnlyDictionary _allAttributes; + /// + /// Gets or sets the CSS class name applied to the NavLink when the + /// current route matches the NavLink href. + /// + public string ActiveClass { get; set; } + /// /// Gets or sets a value representing the URL matching behavior. /// @@ -55,6 +61,7 @@ namespace Microsoft.AspNetCore.Blazor.Routing parameters.TryGetValue(RenderTreeBuilder.ChildContent, out _childContent); parameters.TryGetValue("class", out _cssClass); parameters.TryGetValue("href", out string href); + ActiveClass = parameters.GetValueOrDefault(nameof(ActiveClass), "active"); Match = parameters.GetValueOrDefault(nameof(Match), NavLinkMatch.Prefix); _allAttributes = parameters.ToDictionary(); @@ -92,7 +99,7 @@ namespace Microsoft.AspNetCore.Blazor.Routing { return string.Equals(currentUriAbsolute, _hrefAbsolute, StringComparison.Ordinal); } - else + else { throw new InvalidOperationException($"Unsupported {nameof(NavLinkMatch)} value: {Match}"); } @@ -102,8 +109,9 @@ namespace Microsoft.AspNetCore.Blazor.Routing { builder.OpenElement(0, "a"); - // Set "active" class dynamically - builder.AddAttribute(0, "class", CombineWithSpace(_cssClass, _isActive ? "active" : null)); + // Set class attribute + string classAttrValue = CombineWithSpace(_cssClass, _isActive ? ActiveClass : null); + builder.AddAttribute(0, "class", classAttrValue); // Pass through all other attributes unchanged foreach (var kvp in _allAttributes.Where(kvp => kvp.Key != "class" && kvp.Key != nameof(RenderTreeBuilder.ChildContent))) @@ -118,7 +126,7 @@ namespace Microsoft.AspNetCore.Blazor.Routing } private string CombineWithSpace(string str1, string str2) - => str1 == null ? str2 + => str1 == null ? (str2 ?? string.Empty) // Return an empty string if both str1 and str2 are null : (str2 == null ? str1 : $"{str1} {str2}"); private static bool StartsWithAndHasSeparator(string value, string prefix)