This post will show you how to style the active link in Angular Router with routerLinkActive
and routerLinkActiveOptions
.
routerLinkActive
routerLinkActive
is a directive that adds a CSS class to the element when the link’s route becomes active.
We set a class name active
to the active link, and apply a red background color to the active link. When user click the home or about link, the background color of the active link will change to red.
1 | <ul> |
1 | .active { |
routerLinkActiveOptions
routerLinkActiveOptions
is an input property of routerLinkActive
directive that allows you to set the options for the active link. It provides a finer-grained control over the behavior of the active link.
Let’s take a look at the definition of routerLinkActiveOptions
:
1 | routerLinkActiveOptions: { |
Scenario 1: exact: true
When exact: true
, the active link will only be set when the URL is exactly the same as the link’s URL.
1 | <ul> |
With this settings, when user input /home/123
in the browser, the home link will not be active, since /home
is not exactly the same as /home/123
.
Scenario 2: match fragment
When fragment: 'exact'
, the active link will only be set when the URL’s fragment is exactly the same as the link’s fragment.
1 | const isActiveMatchOptions: IsActiveMatchOptions = { |
1 | <ul> |
With this settings, when user input /home#section1
in the browser, the home link will not be active, since the fragment is not exactly the same as the link’s fragment.
You can also config the matrixParams
, queryParams
, and paths
in the IsActiveMatchOptions
object to control the active link behavior.