Is it possible to utilize a function within an Angular [routerLink] to define the query parameter?

When receiving a response from the API without an ID, it presents data fields like url, name, gender, culture, etc. However, I need to create a route to access specific character information using /characters/:id. Since there is no direct ID provided in the response, I plan to extract it from the URL of the character.

The URL structure looks like this:

https://www.anapioficeandfire.com/api/characters/38

To accomplish this, I intend to retrieve the ID from the URL dynamically. My approach involves utilizing Angular's *ngFor directive to iterate through characters and generate corresponding router links based on their IDs.

<p>Characters:
  <ul>
     <li *ngFor="let character of characters | async">
       <a  [routerLink]="['/characters', getCharacterId(character)]">{{character.name}}</a>
     </li>
  </ul>
</p>

Next steps involve defining a function called getCharacterId() that extracts the necessary ID from the URL:

getCharacterId(character: Character) {
        return character.url.substr(character.url.lastIndexOf("/") + 1);
    }

Answer №1

Consider utilizing a getter or you have the option to use

<ng-container *ngIf="getCharacterId(character) as characterId">
<a [routerLink]="['/characters', characterId]">{{character.name}}</a>
</ng-container>

However, it would be beneficial to create a class from the interface. In the class constructor, assign an ID and when fetching characters from the service, implement something like this:

return http.get<Character[]>('http://some_url').pipe(map(res => (res||[]).map(c => new Character(c))));

By doing this, you will now have an array of mapped classes that may already include the characterID.

Answer №2

By simply clicking on a link, you can trigger a function call.

<a [routerLink]="" (click)="redirect(character)">{{character.name}}</a>

In the component, define the function and then navigate to a specific path with query parameters.

redirect(character){
   const id = character.url.substr(character.url.lastIndexOf("/") + 1);
   this.router.navigate(['/characters'],{ queryParams: { characterId: id}});
}

Answer №3

If you're looking for a solution, consider the following:

 <p>Selected Players:</p>
  <ul>
     <li *ngFor="let player of players | async">
       <a [routerLink]="['/players', player.url.split('/').reverse()[0]]">{{player.name}}</a>
     </li>
  </ul>

To extract the last segment of the URL by splitting it with '/' and reversing it to pick the first one, you can use the code below. Modify this logic as needed:

player.url.split('/').reverse()[0]

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

What is the best way to store items in localStorage within Angular version 4.4.6?

I have been working on implementing a basic authentication system in Angular 4.4 with MongoDB as the backend database. login.component.ts import { Component, OnInit } from '@angular/core'; import { AuthService } from 'app/services/auth.ser ...

Guide to utilizing Sheet Modal in Ionic 5

In the documentation for Ionic version %, there is a showcase of the sheet modal in mobile view but the code examples do not include it. If you want to learn how to use the Sheet Modal feature, you can check out the source code under the Mobile View sectio ...

Angular CLI fails to generate angular-cli.json file

Currently in the process of creating a new PWA and I need to input information into angular-cli.json. Utilizing Angular CLI: 1.7.4 Node: 8.11.1 OS: win32 x64 Angular: 5.2.10. Upon running ng new pwaapp --service-worker, the project folder does not conta ...

The powerful combination of Angular 6, NodeJS, and MongoDB creates a

Hi there. I've been searching around but couldn't find a solution to my problem. There are two similar unanswered questions. I'm new here, so any help with my final project would be greatly appreciated. After running ngForm, I encountered a ...

When using a Redux action type with an optional payload property, TypeScript may raise complaints within the reducer

In my react-ts project, I define the following redux action type: type DataItem = { id: string country: string population: number } type DataAction = { type: string, payload?: DataItem } I included an optional payload property because there are tim ...

Utilizing FileInterceptor with a websocket in NestJs: A Step-by-Step Guide

Is it possible to implement this on a websocket, and if so, how can I achieve that? @UtilizeInterceptors( DocumentInterceptor('image', { location: '../data/profileImages', restrictions: { size: byte * 10 }, ...

Create a new data structure in TypeScript that stores multiple values in a

For my TypeScript project, I came across a situation where I needed to utilize Promise.all(...) to handle an array of multiple items: Promise.all( firstRequest, secondRequest, ..., nthRequest ) .then((array : [FirstType, SecondType, ..., NthType]) ...

"Encountering a 404 error with the angular2-in-memory-web-api

Currently, I am in the process of developing a 5 minute application using Angular 2 with reference to this particular guide: https://angular.io/docs/ts/latest/tutorial/toh-pt6.html. While working on the HTTP section, I encountered a 404 error due to the a ...

Angular Appreciation Meter

Looking to create a rating system using Angular. The square should turn green if there are more likes than dislikes, and red vice versa (check out the stackblitz link for reference). Check it out here: View demo I've tried debugging my code with con ...

Rendering server applications using Angular 6 with Express

Currently, I am working with an Angular 6 application and Express server. I am looking to implement a server rendering system using the best practices available, but I have been struggling to find resources that are compatible with Angular 6 or do not util ...

Iterate over Observable data, add to an array, and showcase all outcomes from the array in typescript

Is there a way to iterate through the data I've subscribed to as an Observable, store it in an array, and then display the entire dataset from the array rather than just page by page? Currently, my code only shows data from each individual "page" but ...

The mysterious case of TypeScript imports making all other code vanish

I have multiple classes located in root/app/providers/engine/engine.ts. In my test specification file spec/engine/engine-spec.ts (the spec/ directory is also where the jasmine support/ resides), I have a simple test: ///<reference path="../../typings/g ...

Dealing with TSLint errors within the node_modules directory in Angular 2

After installing the angular2-material-datepicker via NPM, it is now in my project's node_modules folder. However, I am encountering tslint errors that should not be happening. ERROR in ./~/angular2-material-datepicker/index.ts [1, 15]: ' should ...

How to include a cancel button within a tab component using Angular Material

I recently implemented a tab component with custom label templates. You can view the code and see how it works in this StackBlitz project. My question is, how can I add a cancel button to the top-right corner of the tabs? I don't need the button to do ...

What is the correct way to invoke a method from a generic in TypeScript?

My goal is to develop a function that invokes a specific method on a generic object. Here's my initial attempt: type MethodName<S extends Object, M extends keyof S> = S[M] extends Function ? M : never const callMethod = <S, M extends keyof ...

Angular issue: Unable to implement Bootstrap dropdown in navbar

I've successfully added popper.js, bootstrap, and jquery to my project. Here is my Angular json file configuration: "styles": [ "src/styles.css", "../node_modules/bootstrap/dist/css/bootstrap.min.css" ], "script ...

What is the best approach to organize data from an observable based on a nested key?

I'm currently developing a new application and struggling with grouping data. The data is being pulled from an observable, and I need to group objects by their status and push them into an array. I attempted to use the groupBy() method, but unfortunat ...

Issue encountered while using Typescript with mocha: Unable to utilize import statement outside a module

Exploring the world of unit testing with mocha and trying to create a basic test. Project Structure node_modules package.json package-lock.json testA.ts testA.spec.ts tsconfig.json tsconfig.json { "compilerOptions": { "target&qu ...

Dealing with Uncaught Promises in Angular 2 while injecting a service

I followed the instructions in the official tutorial to start a project, but I'm encountering an issue with injecting services into my Angular2 app. Everything was working fine until I added a service. Here are the files : app.component.ts import ...

Error encountered when attempting to insert data into a PostgreSQL database using Node.js and Sequelize

I'm currently using the node sequelize library to handle data insertion in a postgress database. Below is the user model defined in the Users.ts file: export class User extends Sequelize.Model { public id!: number; public name: string; public ...