skip to content

In Blazor, what does the NavLink component add over a plain anchor, and how do NavLinkMatch.Prefix and NavLinkMatch.All decide when it is active?

level: juniorimportance: should knowfreq 44%

answer

  1. toggles a CSS class
  2. "active" unless ActiveClass is set
  3. Prefix is the default
  4. All for the home link
  5. 10 ignores query and fragment

basics

~20 s

NavLink renders an anchor and adds the active CSS class, or ActiveClass, when its href matches the current URL. NavLinkMatch.Prefix, the default, matches any URL below the href; NavLinkMatch.All needs the whole URL, and in .NET 10 ignores query and fragment.

solid answer

~40 s

`NavLink` renders an ordinary `<a>`, passes through extra attributes, and listens to `NavigationManager.LocationChanged` so it can add a CSS class when its `href` matches the current URL. The class is `active` unless you set `ActiveClass`. The `Match` parameter takes a `NavLinkMatch`: `Prefix` (the default) also marks the link active for deeper paths, so `/plants` lights up on `/plants/12`; `All` requires the same path, which is why the template's home link (`href=""`) uses it. Since ASP.NET Core 10, `All` ignores the query string and fragment, so a catalog link stays active on `/catalog?light=shade`; the `NavLink.EnableMatchAllForQueryStringAndFragment` `AppContext` switch restores the old behaviour. For anything else, derive from `NavLink` and override `ShouldMatch`.

code

razor · 6 lines
razor
<nav>
    <NavLink class="nav-link" href="" Match="NavLinkMatch.All">Home</NavLink>
    <NavLink class="nav-link" href="plants">Plants</NavLink>
    <NavLink class="nav-link" href="catalog" Match="NavLinkMatch.All"
             ActiveClass="current">Catalog</NavLink>
</nav>

go deeper

for a junior

Recall that NavLink adds the active class (or ActiveClass) on a match, that Prefix is the default, and that the home link uses NavLinkMatch.All.

for a middle

Explain how NavLink learns about navigation through LocationChanged, how prefix matching respects segment boundaries, and what changed for All in .NET 10.

for a senior

Show you would catch the .NET 10 query-string change in an upgrade review and choose between the AppContext switch and a ShouldMatch override.

for a principal

Weigh a shared menu component with its own matching rules against framework defaults across many apps, and how upgrade notes reach every team.

## What `NavLink` is `NavLink` (namespace `Microsoft.AspNetCore.Components.Routing`) is a small built-in component for navigation menus. It renders a normal HTML `<a>` element, so the browser, enhanced navigation and the interactive router all treat it like any link. What it adds is **active-state tracking**: it compares its `href` with the current URL and, when they match, adds a CSS class to the rendered anchor. A plain `<a>` cannot do that on its own, because it never learns that the app has moved to another page. It works in every render mode. During static rendering it computes the class once for the requested URL; when interactive, it subscribes to `NavigationManager.LocationChanged` and re-renders after each navigation, unsubscribing when it is disposed. ## Its parameters - `href` and every other attribute (`class`, `target`, `aria-*`) are captured and copied onto the `<a>`. - `ActiveClass` sets the class added on a match. When it is not set, the class is `active`. - `Match` takes a `NavLinkMatch` value and decides what counts as a match. - `ChildContent` is the link text or markup. The nursery's menu shows the two common shapes: ```razor <NavLink class="nav-link" href="" Match="NavLinkMatch.All">Home</NavLink> <NavLink class="nav-link" href="plants">Plants</NavLink> <NavLink class="nav-link" href="catalog" Match="NavLinkMatch.All" ActiveClass="current">Catalog</NavLink> ``` ## Prefix versus All | `NavLinkMatch` | Active when | Typical use | |---|---|---| | `Prefix` (default, enum value 0) | the current URL equals the href or continues it after a separator such as `/` or `?` | a section link: `plants` stays active on `/plants/12/care` | | `All` | the current URL equals the href | the home link, which would otherwise be a prefix of every URL | Two details trip people up: 1. **Prefix respects segment boundaries.** The check requires a separator after the href, so `href="plant"` is not active on `/plants`. 2. **Trailing slash and case.** Comparison is case-insensitive, and a link to `/catalog/` is still treated as matching `/catalog`. ## What changed in ASP.NET Core 10 Before .NET 10, `NavLinkMatch.All` compared the **entire** URL, query string and fragment included. A catalog link with `Match="NavLinkMatch.All"` lost its highlight the moment a filter wrote `?light=shade` into the address bar. ASP.NET Core 10 changed that: - `All` now ignores the query string and the fragment, so the link stays active while the path matches. - To get the old behaviour back, set the `Microsoft.AspNetCore.Components.Routing.NavLink.EnableMatchAllForQueryStringAndFragment` `AppContext` switch to `true`. - `NavLink.ShouldMatch(string uriAbsolute)` is a `protected virtual` method in the shipped public API, so a subclass can supply its own rule and return `true` to apply the active class. ```csharp public sealed class SectionNavLink : NavLink { [Parameter] public string Section { get; set; } = ""; protected override bool ShouldMatch(string uriAbsolute) => uriAbsolute.Contains($"section={Section}", StringComparison.OrdinalIgnoreCase); } ``` ## When to use it, and when not - Use `NavLink` for menus, tabs and breadcrumbs where the user needs to see where they are. - Use a plain `<a>` for links inside content, where an active state means nothing and the subscription is wasted work. - Do not use `NavLink` to *perform* navigation in code; that is `NavigationManager.NavigateTo`. - Remember that the class only changes the markup. Styling it, and exposing the current page to assistive technology with `aria-current`, is the app's job. ## How the href is resolved `NavLink` resolves its `href` with `NavigationManager.ToAbsoluteUri`, which combines it with the app's **base URI** (the `<base href>` in `App.razor`). That matters when the nursery is hosted under a path base such as `/nursery/`: - `href="plants"` resolves to `/nursery/plants`, inside the app, and matches as expected. - `href="/plants"` resolves to `/plants` at the host root, outside the app, so it never matches a page of the app and the link leaves the app when clicked. Write menu links without a leading slash so the same markup works at any base path. ## A loop pitfall When menu entries are generated in a `for` loop, capture the loop variable in a local (`var index = i;`) before using it inside the `NavLink`'s child content. Child content is rendered later, and by then the loop variable has its final value. A `foreach` loop does not have this problem. ## Summary for the interview `NavLink` is an anchor that knows whether it points at the current page. `Prefix` is the default and suits section links; `All` is for exact pages and, since .NET 10, ignores the query string and fragment. `ActiveClass` renames the class, and `ShouldMatch` is the escape hatch for custom rules.

  • Why does a home NavLink with href="" need NavLinkMatch.All?
    With the default `Prefix`, the empty href resolves to the base URI, and every page in the app starts with it, so Home would be highlighted everywhere. `NavLinkMatch.All` makes it active only on the base URL itself.
  • After upgrading to .NET 10, a team's tab strip relies on query strings to mark the active tab and every tab now looks active. What are the options?
    In 10, `NavLinkMatch.All` ignores the query string, so tabs that differ only by `?tab=` all match the same path. Either set the `NavLink.EnableMatchAllForQueryStringAndFragment` `AppContext` switch to `true` to restore full-URL matching, or derive from `NavLink` and override `ShouldMatch` to compare the query value.

  • NavLinkMatch.All is the default, so section links need Match="NavLinkMatch.Prefix"
  • NavLink performs navigation in code, like NavigationManager.NavigateTo
  • In .NET 10, NavLinkMatch.All still loses the active class when the query string changes
  • NavLink renders a button element, so it cannot carry target or other anchor attributes
  • Prefix matching makes href="plant" active on /plants

Assumes ASP.NET Core 10: NavLinkMatch.All ignores the query string and fragment, and NavLink.ShouldMatch is overridable; before 10, All compared the full URL including the query.