Angular router link with active status

Is there a way to implement an active router link with a dynamic list of routes without assigning a fixed route?

I attempted to create a function that sends the index on click and searches for its array position in the sidebar DOM.

Although it worked, when we delete or add another section, it gets lost after updating. Does anyone have alternative ideas?

Current code:

Answer №1

One of the easiest ways to implement dynamic routing in Angular is by utilizing routerLink along with the routerLinkActive functionality. You can achieve this by binding data in the following manner:

Sample Code

const sections = [{name: "Home", link: ["/home", "other"]},{name: "Contact", link: ["/contact"]}]

HTML Implementation

<ul>
  <li *ngFor="let link of sections" routerLinkActive="active" [routerLink]="link.link">{{ link.name }}</li>
</ul>

This approach offers a straightforward solution. However, if you prefer not to use routerLink, you can handle it manually. One method involves using ngClass to dynamically add classes based on certain conditions.

Example Code

activeRoute: string = "";

constructor(
    private activatedRoute: ActivatedRoute) {
    if (activatedRoute.snapshot['_routerState'].url.indexOf("home") > -1) {
      this.activeRoute = "home";
    } 
}

HTML Integration

<ul>
  <li *ngFor="let link of sections" [ngClass]="{ active: activeRoute === 'home'}">{{ link.name }}</li>
</ul>

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

Warning in TypeScript: TS7017 - The index signature of the object type is implictly assigned as type "any"

An alert for TypeScript warning is popping up with the message - Index signature of object type implicitly has any type The warning is triggered by the following code block: Object.keys(events).forEach(function (k: string) { const ev: ISumanEvent ...

Using React and TypeScript to create multiple click handlers for different sections within the same div element

I am a beginner in the world of React, Typescript, and coding in general, so I'm not entirely sure if what I'm attempting is even possible. Currently, I have a donut chart with clickable segments sourced from a minimal pie chart found at: https:/ ...

Searching for similar but not identical results using Knex.js

I am seeking a solution to retrieve similar posts without including the post itself. Here is my approach: export async function getSimilars(slug: string) { const excludeThis = await getBySlug(slug) const posts = await knex('posts') .whe ...

The code is looking for an assignment or function call, but found an expression instead: no-unused-expressions

Why am I encountering an ESLint error when using Ternary with 2 statements here? ESLint Error: no-unused-expressions res?.isSuccessful ? (this.toastService.showToast(res.message, 'success'), this.queueDataService.addMember(attendee)) : ...

Troubleshooting Error in Converting a JSX File with Tailwind CSS and Typescript

I found a code example on the Tailwind website. However, when I changed the file extension to .tsx, I encountered an error related to the className attribute. Do I need to specify a type for the className variable? What steps should I take to resolve thi ...

What methods are available to extract HTML elements from .ts files?

Exploring Angular development has been quite a challenge for me. I've heard that typescript is an extension of javascript, but when it comes to manipulating HTML elements in the .ts file, I seem to be at a loss. I attempted a simple document.getEleme ...

Retrieve the specific type of property from a generic data structure

I am currently working on a project where I need to determine the type of property within a given Type: type FooBarType { foo: string, bar: number } The function would be structured like this: getType<K extends keyof T>(key: K): string. The ...

Exploring the New Features of Angular 13 with Typescript, Regular Expressions, and

Currently, I am working on an Angular 13 project and I am trying to create a directive that will only allow users to type numbers and '/' in my date input field format of dd/mm/yyyy. Below is the regular expression (Regx) that I am using: if (!St ...

Leveraging React's state to enable temporary invalid numeric input handling

My current approach may be flawed, but I aim to have a parent component and a child component, where the child contains an input field for users to enter numbers. The callback function of the parent component will only be triggered for valid numbers, as ve ...

Type to match the data type of the enum, not strictly one specific value

enum X { A = 'x', B = 'y' } type A<T> = { prop1: T prop2: X } let r:A<X> = { prop1: X.A, prop2: X } What specific type must be assigned to A.prop2 in order for only X and no other item to also be assigned to i ...

Jest test encounters import error when attempting to import pure ESM module in TypeScript project

Hello, I am currently facing an issue while trying to utilize the file-type module, which is pure ESM, in a TypeScript project with Jest. Despite following the ESM guidelines outlined here, I continue to encounter a SyntaxError: Cannot use import statement ...

Exploring the contrast between 'null' and an empty string as the fallback value in a TypeScript React component

Here is a Typescript interface that I am working with: export interface Page { description: string | null; } The description field in this interface can be either a string or null. I am curious about the difference between using null vs '' as ...

What is the best way to declare only a portion of a JavaScript module?

I'm having trouble understanding declarations. If I only need to declare a portion of a module, is this the correct way to do it (disregarding the use of 'any')? import { Method as JaysonMethod } from 'jayson/promise'; declare cla ...

What does the 'key' parameter represent in the s3.put_object() function?

Currently, I'm utilizing Boto in my project to upload artifacts to an s3 bucket. However, I am uncertain about the usage of the Key parameter within the put_object() method: client.put_object( Body=open(artefact, 'rb'), Bucket=buc ...

Unable to assign to 'routerLinkActiveOptions' as it is not recognized as a valid property

Lately, I've delved into the world of angular 8. While configuring the routing module in my app.component.html file, everything was smooth sailing except for achieving an ActiveTab using routerLinkActiveOptions on my li item. https://i.sstatic.net/9Z ...

Using FormControl Inheritance in Angular 4

My goal is to enhance the functionality of a FormControl by creating a subclass with additional properties. These properties will then be utilized in custom form controls to modify behavior. I attempted to inherit from FormControl (let's call it Stan ...

Exploring Vue with Typescript - leveraging components without explicit definitions

Has anyone successfully used vue-instant component as a child component before? I'm having trouble adding components without definition. Could it be related to webpack config ignoring node_modules due to lack of type declaration? Here's the code ...

Is there a way to implement several filters on an array simultaneously?

Is it possible to filter an array based on both the input text from the "searchTerm" state and the selected option from the dropdown menu? I am currently using react-select for the dropdown functionality. const Positions = ({ positions }: dataProps) => ...

TypeScript is encountering difficulty locating a node module containing the index.d.ts file

When attempting to utilize EventEmitter3, I am using the following syntax: import EventEmitter from 'eventemitter3' The module is installed in the ./node_modules directory. It contains an index.d.ts file, so it should be recognized by Typescrip ...

Let's compare the usage of JavaScript's toUTCString() method with the concept of UTC date

When I fetch the expiry date time in UTC from the Authentication API along with a token, I use the npm jwt-decode package to extract the information. private setToken(value: string) { this._token = value; var decoded = jwt_decode(value); this._ ...