puddlejumper26 / blogs

Personal Tech Blogs
4 stars 1 forks source link

RouterLinkActive in Angular #42

Open puddlejumper26 opened 4 years ago

puddlejumper26 commented 4 years ago

It is common we need to create some links inside the page. Then it comes sometimes we need to realize the following effect:

ezgif com-gif-maker

keep the selected or focused element as the same status, normally is a button, or a link, It changes only another button, basically a link been clicked, which means the url been changed.

Here we could use RouterLinkActive to solve the problem.

.red{
   background: red;
}

.green{
   background: green;
}

One Class

<a routerLink="/user/bob" routerLinkActive="red">Bob</a>

When the url is either '/user' or '/user/bob', the red class will be added to the a tag. If the url changes, the class will be removed.

Two Classes

<a routerLink="/user/bob" routerLinkActive="red green">Bob</a>
<a routerLink="/user/bob" [routerLinkActive]="['red', 'green']">Bob</a>

Judge

<a routerLink="/user/bob" routerLinkActive="red" [routerLinkActiveOptions]="{exact:
true}">Bob</a>

This will add the classes only when the url matches the link exactly. Only when path is '/user/bob', could not be '/user'

isActive to check Route Status

<a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive">
  Bob {{ rla.isActive ? '(Activated)' : '(Not Activated)'}}
</a>

above rla is routerLinkActive, could be defined as others.

Parent Element

<div routerLinkActive="red" [routerLinkActiveOptions]="{exact: true}">
    <a routerLink="/user/login">login</a>
    <a routerLink="/user/reset">reset</a>
</div>

To add tag a's parent div with routerLinkActive and routerLinkActiveOptions, either the path is /user/login or /user/reset, the parent div will be added with red class. Here the routerLinkActiveOptions needs to be exact,otherwise when the url is /user, the parent element will also be added with red class.

Parent link still actived when on the child element

Please check this example for better understanding https://stackblitz.com/edit/angular-routerlinkactive-shawn

References