How can you specify the active route in Angular?

I am curious about whether it is possible to set the active route from a script instead of just from the HTML template. Let me provide an example:

@Component({
  template: `<input type="button" (click)="back()" value="back" />`
})
export class MyComponent implements OnInit {
  constructor(private someService: SomeService) {}

  ngOnInit(): void {
    this.someService.someObservable$.pipe(first()).subscribe(_ => this.back());
  }

  back(): void {
    // do stuff before navigating back ...
    // navigate to dashboard
  }
}

Any insights are appreciated!

Answer №1

Implement

<li *ngFor="let item of commonData">
   <a [routerLink]="item.link" [ngClass]="{'active': item.name === selectItem}">{{item.label}}</a>
</li>

when transitioning pages or initializing the process, utilize

selectItem = this.activatedRoute.snapshot.routeConfig.path;

Alternatively, you can use the traditional routerLinkActive method with

<li *ngFor="let item of commonData">
    <a [routerLink]="item.link" routerLinkActive="active">{{item.label}}</a>
 </li>

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

Material UI is not capable of utilizing Props

I'm having trouble using the Checkbox component from Material UI. Even though I can't seem to use the normal props like defaultChecked or size="small", as it gives me the error TS2769: No overload matches this call. TS2769: No overload ...

The dispatch function of useReducer does not get triggered within a callback function

Can anyone assist me with this issue I am facing while using React's useReducer? I'm trying to implement a search functionality for items in a list by setting up a global state with a context: Context const defaultContext = [itemsInitialState, ...

Can you guide me on how to record a value in Pulumi?

According to Pulumi's guidance on inputs and outputs, I am trying to use console.log() to output a string value. console.log( `>>> masterUsername`, rdsCluster.masterUsername.apply((v) => `swag${v}swag`) ); This code snippet returns: & ...

Error: Unable to assign void to parameter type

Encountering TypeScript Error: Argument type (response: Response<DSBMannschaftDTO[]>) => void is not assignable to parameter type ((value:Response<DSBMannschaftDTO[]>) => (PromiseLike<void> | void)) null | undefined | undefined ...

What is the correct way to link an array with ngModel using ngFor loop in Angular?

Utilizing ngModel within an ngFor iteration to extract values from a single input field like this : <mat-card class="hours" > <table id="customers"> <thead > <th >Project</th> ...

The mapStateToProps function in a Higher Order Component is receiving an OwnProps argument with a property that is not defined

I'm a new user of react-redux trying to connect a higher-order component to the react-redux store. In the mapStateToProps function, I'm using the ownProps argument to filter the state. However, the property I'm trying to use within OwnProps ...

An unexpected error occurred while running ng lint in an Angular project

I've encountered an issue while trying to run ng lint on my Angular project. After migrating from TSLint to ESLint, I'm getting the following error message when running ng lint: An unhandled exception occurred: Invalid lint configuration. Nothing ...

What is the best way to trigger a useReducer dispatch function from a different file that is not a React component, without relying on Redux?

In my project, I have a function component that shows a game board named "EnemyBoardComponent.tsx" const enemyBoardReducer = (state:number[][], action:Action)=>{ switch(action.type){ case "update": { return EnemyBoard.getGrid(); ...

TypeScript Error 2304: Element 'div' is nowhere to be found - CRA TypeScript Template

I'm experiencing a problem in VSCode while working on the default create-react-app my-app --template typescript project. It seems to not recognize any HTML elements, as I keep getting the error cannot find name xxx, where 'xxx' represents th ...

A function in Typescript that dynamically determines its return type based on a specified generic parameter

Currently, I am attempting to create a function where the return type is determined by a generic argument. Let me share a code snippet to illustrate: type ABCDE = 'a' | 'b'; function newFunc<U extends ABCDE>(input: U): U extends ...

Make sure that every component in create-react-app includes an import for react so that it can be properly

Currently, I am working on a TypeScript project based on create-react-app which serves as the foundation for a React component that I plan to release as a standalone package. However, when using this package externally, I need to ensure that import React ...

Symfony using Vite with Vue 3 encounters an error: Uncaught ReferenceError - exports is undefined

Currently, I am in the process of developing a Symfony 3 Application with Vite and Vue3 integrated with TypeScript. To replace Symfony's Webpack Encore, I opted for the Vite Buildtool using this convenient plugin: https://github.com/lhapaipai/vite-bu ...

Using an Angular interface for an HTTP request: The statusText message reads as "Error: Unable to Determine."

I've been working on calling an API as an example in Angular using an interface. The API I'm trying to access is located at https://jsonplaceholder.typicode.com/posts. Unfortunately, I encountered the following error message: ERROR HttpErrorResp ...

What is the best way to determine the final letter of a column in a Google Sheet, starting from the first letter and using a set of

My current approach involves generating a single letter, but my code breaks if there is a large amount of data and it exceeds column Z. Here is the working code that will produce a, d: const countData = [1, 2, 3, 4].length; const initialLetter = 'A&a ...

What is the best method for extracting individual JSON objects from a response object and presenting them in a table using Angular?

After receiving a JSON Array as a response Object from my Java application, I aim to extract each object and display it on the corresponding HTML page using TypeScript in Angular. list-user.component.ts import { HttpClient } from '@angular/common/h ...

The correct way to assign a value within an Angular Observable subscribe function

Having some trouble with a basic form using @angular/material (although the material aspect shouldn't make a difference) that is structured like this: <div *ngIf="user"> <form> <mat-form-field> <m ...

Angular 2 file upload encountering CORS issue leading to 401 unauthorized error

Encountered a "401 Unauthorized" error in Chrome and Firefox while attempting to upload files using angular 2 CLI to an apache2-server with a PHP backend. Despite trying three different node modules, the issue persists from the OPTIONS-preflight stage, ...

Vetur is experiencing issues with template functionality, such as not properly checking data and methods

I have incorporated the vetur extension into my Visual Studio Code for a Vue project using TypeScript. I recently discovered that vetur has the capability to perform type checks within the template tag for props, methods, and even variables. However, in ...

Using a split string to destructure an array with a mix of let and const variables

There is a problem with TS: An error occurs stating that 'parsedHours' and 'parsedMinutes' should be declared as constants by using 'const' instead of 'prefer-const'. This issue arises when attempting to destructure ...

Stop the transmission of ts files

Recently, I noticed that when using node JS with Angular-CLI, my .ts files are being transmitted to the client through HTTP. For example, accessing http://localhost/main.ts would deliver my main.ts file to the user. My understanding is that ts files are s ...