3

I can use ngClass to apply a CSS class based on the value of a boolean. However, can I do the opposite? Is it possible to change the value of a boolean based on the existence of a CSS class? Looking around, I cannot find a way to do this in Angular templates.

For context, I'm using routerLinkActive to apply a class if the link is active. What I actually need to do is set a boolean value if the link is active.

6
  • Any specific reason for doing this? Commented Aug 31, 2018 at 21:59
  • By 'link is active' do you mean if a component is displayed? What would the final purpose be? Commented Aug 31, 2018 at 22:02
  • You can check the current route using the Router class, and just check the value in your .ts file Commented Aug 31, 2018 at 22:20
  • @SiddharthAjmera I have a sidenav with categories, and links belonging to those categories. I expand or collapse the category based on a boolean value. Essentially, I am trying to have the category automatically expanded on page load if the current link is within that category. Commented Aug 31, 2018 at 23:36
  • @SebastianG I mean the router link is active, my above comment gets more into what my rationale is. Commented Aug 31, 2018 at 23:38

1 Answer 1

6

The routerLinkActive directive actually has an isActive property you can use.

For example, if we have the following links:

<a routerLink="/one" routerLinkActive="active" #one="routerLinkActive">One</a>

<a routerLink="/two" routerLinkActive="active" #two="routerLinkActive">Two</a>

Here, i've added a reference on each link to their routerLinkActive directive, using the #name="routerLinkActive" syntax. As such, we can now reference the isActive property like so:

<span *ngIf="one.isActive">ONE IS ACTIVE</span>
<span *ngIf="two.isActive">TWO IS ACTIVE</span>

Here it's being used to pass a boolean to *ngIf, but you can use it anywhere you'd like access to that boolean property.

Here is a Stackblitz demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.