Add `ActiveClass` option to NavLink component

This commit is contained in:
Austin Cummings 2018-03-16 11:50:14 -07:00 committed by Steve Sanderson
parent 1626b3b8c8
commit 30ec582767
1 changed files with 12 additions and 4 deletions

View File

@ -32,6 +32,12 @@ namespace Microsoft.AspNetCore.Blazor.Routing
private string _hrefAbsolute;
private IReadOnlyDictionary<string, object> _allAttributes;
/// <summary>
/// Gets or sets the CSS class name applied to the NavLink when the
/// current route matches the NavLink href.
/// </summary>
public string ActiveClass { get; set; }
/// <summary>
/// Gets or sets a value representing the URL matching behavior.
/// </summary>
@ -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)