What is the best way to transfer an object to a component through Angular routing?

In my "home" component, I have an array called mangas containing a list of objects that I iterate through like this:

<div *ngFor="let manga of mangas">
  <h1> {{ manga.title }} </h1>
  <button routerLink="/manga/{{ manga.title }}"> read the manga </button>
</div>

(this is just a simplified example)
Now, my question is how can I pass only the specific "manga" object to the new route instead of passing the entire array?

Answer №1

If you're looking to pass an object to a router (rather than a simple parameter), the key is using "states". Check out this link for more details.

<div *ngFor="let manga of mangas">
  <a routerLink="/manga" [state]="manga">
</div>

In your ngOnInit, make sure you access it there. When using state to retrieve an object, typically you want the router to redirect to "home" if no object is present. If your manga object has a property named mangaId, you can utilize this information within the subscription.

constructor(public activatedRoute: ActivatedRoute) {}
  
ngOnInit() {
  this.activatedRoute.paramMap
    .pipe(map(() => window.history.state)).subscribe(res=>{
          console.log(res) // Check for additional property:navigationId
          // Verify if an object was passed
          // For instance, if your manga object has a property mangaId and it's not equal to 0
          if (!res.mangaId) 
             router.navigate(['/home']                             
     })
}

Answer №2

It is recommended not to pass the object itself in the route, but instead pass the ID of the object and then fetch the object from a data store.

<div *ngFor="let manga of mangas">
  <h1> {{ manga.title }} </h1>
  <button routerLink="/manga/{{ manga.id }}"> 
     read the manga 
  </button>
</div>

To follow the principles of a single page application, consider having a manga service (repository) that handles the management of the manga collection.

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

How can I make the snackbar open multiple times in a row?

Check out this codesandbox I created to show an issue. When you click the button, a MUI snackbar opens. However, if you close it and try to reopen it, nothing happens. Do you think the problem is related to how I'm using hooks? Explore the sandbox h ...

Guide to asynchronously loading images with Bearer Authorization in Angular 2 using NPM

I am in search of a recent solution that utilizes Angular2 for my image list. In the template, I have the following: <div *ngFor="let myImg of myImages"> <img src="{{myImg}}" /> </div> The images are stored as an array w ...

Encountering a 404 error in Angular 9 when refreshing the browser

Encountering a 404 error when attempting to access mysite.com/menu directly, but no issues when navigating through the homepage and selecting the menu option. Tried implementing an .htaccess file following Angular documentation, yet problem persists. Cur ...

The 'Group' property is not found within the type 'ForwardRefExoticComponent<InputProps & RefAttributes<HTMLInputElement>>'

I'm encountering a problem while trying to bind a react hook form on radio and radio group. The issue I'm facing is as follows: Property 'Group' does not exist on type 'ForwardRefExoticComponent<InputProps & RefAttributes< ...

The request made using the Http GET method and specifying a header option is resulting in an

When making an http.get call, I am passing the access_token in the header. However, I keep receiving a 401 Unauthorized error. Strangely, I am able to successfully retrieve data from the API using the access_token in Postman. It's important to note t ...

An endless loop is occurring, preventing the form control value from being updated using a global service. This results in an error message indicating that the maximum stack size

<input class="form-control dateicon" maxlength="10" minlength="10" [maxDate]="api.maxDate" name="xyz" (ngModelChange)="def($event,2)"[bsConfig]="{ isAnimated: true ,dateInputFormat: 'DD/MM/YYYY'}" formControlName="abc" bsDatepicker placeholder ...

Angular 11.0.3 displaying ngClass issue (Unable to bind ngClass as it is not recognized as a property of div)

While working on an angular project, I implemented a light and dark theme using mat-slide-toggle to switch between themes. The theme is stored as a boolean called isDark in a Behavioral Subject service. There are two lazy-loaded modules - one for the home ...

Adjusting box width based on device type: desktop and mobile

I'm currently working on a form that includes several mat-form-fields. I have set the width of these items to 750px, but this does not work well for mobile devices. I am trying to figure out how to make the form or mat-form-field automatically adjust ...

Resetting the state back to its initial value - which one to use: useState or useReduce?

In order to enhance the functionality of a third-party Authentication service Auth0's useAuth0 hook, I have developed a custom hook called useAuth. This custom hook is responsible for managing local variables that store essential user information like ...

Implementing captivating animations in Angular2 for an *ngFor loop can add a unique

Exploring the Angular2 documentation has left me stumped on how to incorporate delays into animations. My goal is to achieve a similar effect to this jQuery plunkr example. I am utilizing Angular2's animation capabilities in generating these "bars" w ...

Classes in Typescript can implement interfaces to streamline the functionality

Recently, I've been working on creating my custom class called AxiosError and I can't help but feel like the code is a bit repetitive. //types.ts export interface IAxiosRequest{} export interface IAxiosResponse{} export interface IAxios ...

Uncovering the mystery of retrieving form values from dynamic HTML in Angular 2

As a beginner in Angular 2, I am facing challenges extracting values from Dynamic HTML. My task involves having some Form Inputs and injecting Dynamic HTML within them that contain additional inputs. I followed the example by @Rene Hamburger to create the ...

Steps to execute an Angular directory within a project

Click here for imageWhenever I try to run ng serve command from the directory, it doesn't seem to work and just takes me back to the same directory. I'm having trouble running my Angular project. Any suggestions on how to solve this issue? ...

Ways to validate email input with pattern in Angular 2

I need help figuring out how to use the email pattern error for validation using the hasError function in Angular 2. My goal is to apply the invalid class to my input field. Below, you can see the code from registration.component.html: <div class="inpu ...

How can I limit the keys in a Typescript object to only certain strings?

Is there a way in Typescript to create an object of type Partial with keys that can only be a combination of 'a', 'b', or 'c'? The object should not have all 3 keys, but it must have at least one. Here's what I've at ...

Updating Radio Button Value in React Using TypeScript Event Handler

Whenever I try to save different values to the state, I encounter an issue where selecting female results in the male radio button being selected, and vice versa. Do you think it would be better to use a generic 'gender' variable in the state in ...

Exporting Types in an NPM Package: Best Practices

Struggling to create a private NPM package for internal use within my company's Nodejs applications using Typescript. Currently, I have a basic proof of concept with some constants, but I'm having trouble structuring it in a way that is importabl ...

What could be the reason for the route animation failing to work in Angular2?

App.module: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from "@angular/http"; import { BrowserAnimat ...

Concealed URL - Navigation with Angular 2 Routing

Is it possible to conceal the URL when using window.open()? Alternatively, can the Angular2 router be utilized to open the URL in a fresh tab? I am familiar with the method of concealing the URL during routing by using this.router.navigate(["/Pages"], { s ...