Retrieve the value of [routerLinkActive] in the component's class

Recently, I've been working on a tab component called TabComponent and it includes the following HTML template:

<a [routerLink]='link' [routerLinkActive]="[is-active]">link label</a>
<button>Close tab</button>

The challenge I'm facing is how to access the value of the [routerLinkActive] property within the component class. Essentially, I need to retrieve a variable that indicates whether this routerLink is currently active. Any suggestions on how to achieve this?

UPDATE: I have started thinking that if I could somehow access the CSS class of the <a> link tag, it might solve my problem. Is there a way to do this?

Answer №1

If you're looking to extract values from your template, here's a helpful tip:

<a *ngFor="let child of directory; let i = index;"
   routerLink="{{child.route}}"
   routerLinkActive #rla="routerLinkActive">

   <h3>{{rla.isActive}}</h3><!--This will show a boolean indicating if you are on this link-->
</a>

By including the above code in your template, the h3 element will reflect whether you are currently on the linked page.

Although this method works within the template, I've encountered difficulties passing this value to component.ts or to other directives in the template:

<a *ngFor="let child of directory; let i = index;"
   routerLink="{{child.route}}"
   routerLinkActive #rla="routerLinkActive"

   [active]="rla.isActive" <!--Unfortunately, this doesn't insert the boolean as expected-->
   >    
   <h3>{{rla.isActive}}</h3>
</a>

I hope this information proves useful. Feel free to share any progress made towards finding a solution.

Answer №2

If you want to access the isActive state within a component, you must wait for the AfterContentChecked lifecycle hook.

<a routerLink="/user/john" routerLinkActive #rla="routerLinkActive">
  John {{ rla.isActive ? '(active)' : ''}}
</a>
@ViewChild('rla') private rla: RouterLinkActive;

ngAfterContentChecked(): void {
    if (this.rla?.isActive) {
        console.log('isActive')
    }
}

Answer №3

To access routerLinkActive, you can utilize the @ViewChild() decorator.

@ViewChild(RouterLinkActive) private routerLinkActive: RouterLinkActive;

The issue lies in the fact that its values are not immediately set. This means that during component rendering, isActive will likely be false initially, with the Router only updating it to true later on.

Answer №4

In addition to Nayfin's response, I have also successfully implemented this method in Angular 11.

This technique involves using a template variable to assign a property, rather than utilizing ngFor. It is important to note that a unique template variable must be used for each component.

<a routerLink="/route1" routerLinkActive #route1RLA="routerLinkActive" [active]="route1RLA.isActive">Route 1</a>
<a routerLink="/route2" routerLinkActive #route2RLA="routerLinkActive" [active]="route2RLA.isActive">Route 2</a>
<a routerLink="/route3" routerLinkActive #route3RLA="routerLinkActive" [active]="route3RLA.isActive">Route 3</a>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a series of image files from CSS and Javascript animations using Selenium in Python

Looking to convert custom CSS3/Javascript animations into PNG files on the server side and then combine them into a single video file? I found an interesting solution using PhantomJS here. As I am not very familiar with Selenium, adapting it for use with S ...

Determine the total quantity of colored cells within a row of an HTML table and display the count in its own

I need assistance with a table that has 32 columns. From columns 1 to 31, I am able to fill in colors by clicking on the cells. However, I now want to calculate and display the number of cells that are not colored in the last column. This task must be co ...

When compiling my TypeScript file, I encountered an error stating that a block-scoped variable cannot be redeclared

In my Visual Studio Code, I have written just one line of code in my ex1.ts file: let n: number = 10; Upon compiling using the command tsc ex1.ts, the compiler successfully generates the ex1.js file. However, VSC promptly displays an error in the .ts file ...

Is there a way to manipulate the DOM without relying on a library like jQuery?

My usual go-to method for manipulating the DOM involves jQuery, like this: var mything = $("#mything"); mything.on("click", function() { mything.addClass("red"); mything.html("I have sinned."); }); Now I am looking to achieve the same result usin ...

Alter the color of the text within the `<li>` element when it is clicked on

Here is a list of variables and functions: <ul id="list"> <li id="g_commondata" value="g_commondata.html"> <a onclick="setPictureFileName(document.getElementById('g_commondata').getAttribute('value'))">Variable : ...

How to extract data from URLs in Angular

Looking into how to extract a specific value from the URL within Angular for parsing purposes. For example: http://localhost:1337/doc-home/#/tips/5?paginatePage=1 The goal is to retrieve the value "5". HTML snippet: <a href="#/tips/comments/{{ tip ...

Step-by-step guide to creating a dynamic button that not only changes its value but also

I am trying to implement a translation button on my website that changes its value along with the text. Currently, I have some code in place where the button toggles between divs, but I am struggling to make the button value switch as well. Given my limit ...

The values in my JavaScript don't correspond to the values in my CSS

Is it possible to retrieve the display value (display:none; or display:block;) of a div with the ID "navmenu" using JavaScript? I have encountered an issue where I can successfully read the style values when they are set within the same HTML file, but not ...

The function google.script.run encounters an error when dealing with file inputs

For the past two years, my Google Apps Script connected to a spreadsheet has been working flawlessly. I created an HTML form to upload CSV and Excel files for processing and data loading into the spreadsheet. However, since March 2020, file uploading has b ...

What is the best way to avoid special characters in Angular Date pipe?

I have a query that might have been addressed on SO before. However, none of the solutions provided so far have helped me. Therefore, I am posting this question in hopes of finding an answer: I am trying to format a string and escape the h letter within i ...

Error in Java script due to the combination of Jmeter and Selenium APIs

While using Jmeter in conjunction with Selenium WebDriver, I encountered an unhandled error "016/02/17 16:51:47 ERROR - com.googlecode.jmeter.plugins.webdriver.sampler.WebDriverSampler: :14:94 Expected , but found ; WDS.browser.findElement(pkg.By.cssSele ...

Develop a custom directive that incorporates ng-model and features its own distinct scope

UPDATE - I have generated a Plunker I am in the process of developing a personalized directive to be utilized for all input fields. Each input will have distinct options based on the logged-in user's requirements (mandatory, concealed, etc), so I bel ...

What is the reason for browsers changing single quotation marks to double when making an AJAX request?

Jquery: var content = "<!DOCTYPE html><html lang='en'><head><meta charset='utf-8'><meta http-equiv='X-UA-Compatible' content='IE=edge'><meta name='viewport' content='w ...

What is the most effective method to arrange absolute divs generated randomly in a grid-like formation?

Hey there! I'm facing an intriguing challenge with my app. It's designed to generate a variable number of divs which are always in absolute positioning. Unfortunately, making them relative is not an option due to some other factors within the app ...

What is the method to retrieve the exact value of {match.params.id} in React Router?

This is an example of code that I have. However, I am unsure about how to extract the value and utilize it afterwards. class CustomView extends Component { componentDidMount() { var uniqueId = {match.params.id} } render() { ...

Utilizing the 'PUT' update technique within $resource

Hey there, I'm pretty new to Angular and looking for some guidance on how to implement a PUT update using angular $resource. I've been able to figure it out for all 'jobs' and one 'job', but I could use some assistance with in ...

Differences between useFormState and useForm in Next.js version 14

Currently, I am intrigued by the comparison between using the react hook useForm and the react-dom useFormState. The Nextjs documentation suggests utilizing useFormState, but in practice, many developers opt for the react hook useForm. I am grappling with ...

Change the format into a PHP array

In my workplace, I am confronted with a frustrating system that generates the following output: { party:"bases", number:"1", id:"xx_3039366", url:"systen01-ny.com", target:"_self", address:"Ch\u00e3o as Alminhas-Medas,Uteiros ...

Attempting to leverage the combination of mocha, ES6 modules, and ts-node while utilizing the --experimental-loader option

I've been attempting to make the ts-node option --experimental-loader function alongside mocha, but so far I haven't had any success. Before I started compiling ES6 modules, running mocha tests was as simple as: "test": "nyc --reporter=html mocha ...

The best approach to incorporating interactive animation in next.js

My vision is to develop a character creation application using next js. The app should empower users to customize the character using sliders and gender selection buttons. The ultimate goal is to have a 2D animated version of the character that dynamicall ...