Use "link.path" as a reference when redirecting to the home page with [routerLink]

In my application, I utilize a typescript file to set up links and use ngFor within the template to iterate through these links and construct a navigation bar. Each link object contains a property called link.path which specifies the path to redirect to. To redirect to the required path, I use [routerLink], but encountered an issue when not at the root URL. I aim to achieve functionality similar to what is discussed in this thread, where the child route is appended to the root of the application.

However, after modifying my implementation to:

[routerLink]= '["/link.path"]'

Upon clicking, I am directed to <URL>/link.path instead of

<URL>/<name under link.path>
, resulting in a not found error.

How can I adjust my expression above to display the actual value inside this parameter rather than treating it as a string?

component.ts

// imports, class declarations, etc...

  * @property {array} links
  */
  links: Array<{ text: string, path: string }>;

  /**
  * The constructor for the toolbar component initializes TranslatePipe, dynamic routing, router,
  * and dynamically adds routes to the router and dynamicRouting service.
  * @param translate
  * @param router
  * @param dynamicRouting
  *
  */
  constructor(private translate: TranslatePipe, private router: Router, private dynamicRouting: DynamicRoutingService) {
    this.router.config.unshift(
      { path: 'knowledge-base', component: DummyComponent },
      { path: 'home', component: DummyComponent },
      { path: 'settings', component: DummyComponent }
    );
    this.dynamicRouting.addItem({ text: "home", path: "home" });
    this.dynamicRouting.addItem({ text: "knowledge_base", path: "knowledge-base" });
    this.dynamicRouting.addItem({ text: "settings", path: "settings" });
  }
  /**
  * Upon initialization, this function fetches the links and inserts the translated
  * text and path to be used by the template
  *
  * @param
  * @return
  */
  ngOnInit() {
    this.links = [];
    let rawData = this.dynamicRouting.getLinks();
    let self = this;
    rawData.forEach(function(data) {
      let text = self.translate.transform("generic[toolbar][categories][" + data.text + "][label]");
      self.links.push({ text: text, path: data.path });
    });

  // Additional methods...

html

<app-header
  [fixed]="true"
  [navbarBrandFull]="{src: 'assets/logo.png', width: 143, height: 36, alt: 'RT Logo'}"
  [navbarBrandMinimized]="{src: 'assets/logo2.png', width: 35, height: 35, alt: 'RT Logo'}"
  [sidebarToggler]="'lg'">
  <ul class="nav navbar-nav d-md-down-none" routerLinkActive="active">
    <li class="nav-item px-3" *ngFor="let link of links">
      <a class="nav-link" [routerLink]='["/link.path"]'>{{ link.text }}</a>
    </li>
  </ul>
  <ul class="nav navbar-nav ml-auto">
  </ul>
</app-header>

Answer №1

When working in Angular, you have the ability to construct URLs using any path by utilizing [routerLink]. This feature allows you to input string tokens or variables to create the final path.

[routerLink]="['/', var, 'str']" = /var/str

<a class="nav-link" [routerLink]='["/", link.path]'>{{ link.text }}</a>

To learn more about RouterLink in Angular, refer to the official documentation: https://angular.io/api/router/RouterLink

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

Unleashing the power of Typescript enums in conjunction with external modules through browserify

Previously, I utilized TypeScript internal modules and included numerous script tags to initialize my app. Now, I am in the process of transitioning the project to utilize external modules (using browserify), but I have hit a roadblock when it comes to con ...

Steps for converting TypeScript code to JavaScript using jQuery, without the need for extra libraries or frameworks like NPM

My single-page dashboard is quite basic, as it just displays weather updates and subway alerts. I usually refresh it on my local machine, and the structure looked like this: project/ index.html jquery-3.3.1.min.js script.js I decided to switch it t ...

What kind of parameter can be specified for a generic method that will not actually be called?

Currently, I am attempting to create a method that includes a parameter with a generic type. In this case, I have used 'unknown' as the generic type since it is not needed: function f(op: Operation<unknown>): void {...}. However, this appro ...

Tips for reducing redundant API requests while using NgRx

I'm facing an issue with my application that has 2 menu items; Teams and Players. Every time I switch between them, an unnecessary API call is made even though the data is already stored. Here is the effects file: loadTeams$ = createEffect(() => { ...

Cypress is unable to drag a customized angular cdkDragHandle functionality

My mind is unraveling due to this issue. I have a drag and drop list in my application with a customized drag handle, but Cypress seems incapable of dragging it. When manually dragged by the user, everything works flawlessly. Below is the simple component ...

What causes a typed string literal to be recognized as a pure string in TypeScript?

Consider the TypeScript code below: type example = 'BOOLEAN' | 'MULITSELECT' | ''; interface IObjectExample { a: string, readonly b: example } const handleObj = (obj: IObjectExample) :void => { console.log(&ap ...

Exploring the capabilities of Vue combined with Typescript and Audio Worklets

I've encountered a challenge with configuring Vue to compile audio worklets. Specifically, I am facing a similar issue to this problem that has already been resolved, but using Typescript instead of JavaScript. My approach was to include the ts-loader ...

Can my https.post function determine the specific API function to call?

Here is the code for my service file that interacts with mongoDB: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { filter, isEmpty, map } from 'rxjs/operators'; import { ...

Creating trendy designs with styled components: A guide to styling functional components as children within styled parent components

I am looking to enhance the style of a FC styled element as a child inside another styled element. Check out the sandbox example here const ColorTextContainer = styled.div` font-weight: bold; ${RedBackgroundDiv} { color: white; } `; This resul ...

Initial binding of Angular2 ControlGroup valueChanges event

My form contains <input type="text"> elements and I've noticed that ControlGroup.valueChanges is triggered during initial data binding when using [ngFormModel] and ngControl. As a result, it gives the impression to the user that the form has al ...

The exported class does not properly recognize the input values, causing them to be displayed as Undefined and triggering an error

Currently working with Ionic Framework version 6.13.1, I have two services set up in a similar code structure. One is the appointment.service.ts, and the other is the registration.service.ts. Each service corresponds to its own TypeScript file containing a ...

It appears that I am encountering an issue when attempting to utilize the async pipe operator

<div class="image" *ngFor="let entry of (currentUserData | async)?.entries"></div> Error message: The term 'currentUserData' is not recognized. Please check the component declaration, template variable declarations, and element refe ...

The Angular 4 HTTP patch method is encountering difficulties when called in code but functions properly when tested using Post

My attempts to make a patch and post call to the server are failing as it never reaches the server. Interestingly, the same request works flawlessly in Postman, so I suspect there might be an issue with my code. Both my post and patch methods are essentia ...

I am trying to access a value saved in a service in Angular 8 component and use it in other services. Can anyone help

Setting a value through a component export class UniqueComponent { constructor(service:UniqueService){ } count =0 ; onRefresh(){ this.service.count = 1; } } Using the value in the service UniqueService{ count:any; doSomething(){ //using count ...

Completing a submission form in a separate module

I've developed a model-based form within a component, but the submit button is located in a different component. When the button is pressed, the following function is activated: @Input() form: any; ... if(this.form.valid) this.saveD ...

Designing a TypeScript class that incorporates an interface

Struggling to grasp the correct syntax, I am looking to incorporate an interface into my project. The desired interface for implementation is as follows: interface Test { [name : string] : (source : string) => void; } My understanding is that this ...

Is there a way to cancel or undo a transaction in the middle of using the PayPal JavaScript SDK?

As a newcomer to Angular, I am working on integrating PayPal as a payment gateway. However, I am unsure of the correct procedure to follow. paypal .Buttons({ createOrder: (data, actions) => { return actions.order.create({ purchase_ ...

Angular Material Table encounters issues with Pagination, Sorting, and Filtering when handling large JSON dataset

I have been encountering an issue where I am attempting to transmit JSON data with over 50,000 entries from an express server to Angular. While the deployment displays all the entries in an Angular Material table format, the features such as pagination, so ...

Experiencing problems with npm installation while trying to compile Angular2 source code

I am trying to compile angular2 source code on my Windows 8.1 x64 development machine. The versions of Node and Npm I have are as follows: Node version 5.1.0 Npm version 3.3.12 1) Successfully cloned the repository 2) Executed bower install command - S ...

The error message "Property 'pipe' is not found on 'ReadableStream<Uint8Array>'" indicates that the pipe method cannot be used on the given type

Within a function resembling Express.js in Next.js, I am working on fetching a CSV file with a URL that ends in .csv. Using the csv-parser library to stream the data without persisting the file and transform it into an array. Here is an excerpt of the code ...