Ways to navigate to a different component while passing along the specific chosen information

After clicking on a specific card, it routes to a different component, but I also want to pass the data of that card to the new component. You can check out a working demo on StackBlitz here.

Answer №1

To find the solution, consider utilizing a shared service

import { Injectable } from '@angular/core';

@Injectable()
export class SharedService {

  selectedData;
  constructor() { }

  public setSelectedData(data) {
    this.selectedData = data;
  }

  public getSelectedData(): any {
    return this.selectedData;
  }

}

dashboard.component.ts

import { Component, OnInit } from '@angular/core';
import { SharedService} from '../shared.service'

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {

  item;
  constructor(private sharedService: SharedService) { }

  ngOnInit() {

    this.item = this.sharedService.getSelectedData();
  }

}

table.component.ts

export class TableComponent implements OnInit {
  items = [];
  constructor(private myService: DataService, private router : Router, private sharedService: SharedService) {}

   ngOnInit() {
    this.myService.getItems()
      .subscribe((res :[]) => this.items = res);
  }

  onItemClick(index) {

    this.sharedService.setSelectedData(this.items[index]);
    this.router.navigate(['/dashboard']);
  }

}

table.component.html Invoke the onItemClick() with index

<mat-card (click)="onItemClick(i)" >

Check out this modified stackblitz demo

Answer №2

To securely share data across components, it is essential to utilize a shared service that allows for communication through setters and getters or observables.

  1. Start by creating a dedicated shared service
  2. When the card is clicked, store the data in the shared service
  3. Upon navigating to a different component, retrieve the data from the shared service either by using a getter method or subscribing to an observable

If only the ID needs to be transferred, consider utilizing path parameters or query parameters. However, avoid passing excessive information through the URL to enhance security.

Implementation of SharedService:

export class SharedService {
  public $cardDataSubject;

  constructor() {
    this.$cardDataSubject = new Subject();
  }

  setCardDetails(cardDetails) {
    this.$cardDataSubject.next(cardDetails);
  }
}

In the child component, subscribe to the shared service:

constructor(private sharedService: SharedServic) {
    this.$cardDataSubject.subscribe(cardDetails => this.cardDetails = cardDetails);
}

Answer №3

Looking for a solution? Check out this link: How to pass data to Angular routed components?

Best Solution: implement the 3rd approach which involves using a service.

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

I am looking to display data in Angular based on their corresponding ids

I am facing a scenario where I have two APIs with data containing similar ids but different values. The structure of the data is as follows: nights = { yearNo: 2014, monthNo: 7, countryId: 6162, countryNameGe: "რუსეთის ...

Utilizing Variables in TypeScript to Enhance String Literal Types

Here are my codes: export const LOAD_USERS = 'LOAD_USERS'; export const CREATE_USER = 'CREATE_USER'; export interface ACTION { type: string, payload: any } I am trying to limit the possible values for ACTION.type to either 'L ...

Unable to see Next.js page in the browser window

I have set up a next.js project with App Router and my file structure under the app folder looks like this: *some other files* . . user | [id] | | page.tsx | @users | | page.tsx | layout.tsx | page.tsx I am ...

Achieving selective exclusion of specific keys/values while iterating through an array and rendering them on a table using Angular

Currently facing a hurdle and seeking advice I am developing an angular application that fetches data from an API and presents it on the page The service I am utilizing is named "Api Service" which uses HTTPClient to make API calls apiservice.service.ts ...

The parameter cannot be assigned the readonly type 'X' in this context

I encountered an issue with a third-party library where the class structure changed. Initially, it was defined as: export class Foo { field: X[]; …. } In my code, I was working with this type: print(foo.field) After updating to a new version, the c ...

What distinctions can be made between extends and mixins in the context of the vue-class-component library?

Heads-up: Our Vue 2 setup is currently not utilizing the Composition API and we have no immediate plans to do so. This discussion focuses on vue-class-components. Query: The guide for vue-class-components mentions that we can employ a "normal" extends to ...

Encountering an error on Ionic 4, Angular 8: Unable to access property 'subscribe' of undefined

I have a project that utilizes Ionic 4 and Angular 8. The project requires integration with a payment gateway service, which I am accomplishing using the Ionic 4 InAppBrowser plugin to open the payment gateway site. This is how I've implemented it: ...

Unable to modify the text in the input field as the input element cannot be located, despite its presence

Currently, I am running some tests on a web service using Selenium. An issue I encountered is that certain elements get altered by Angular, making it difficult to interact with them as expected. One specific problem I faced was trying to modify text in wha ...

What measures can I take to protect the use of React components that may not be present?

For my project, I am planning to receive icons/svgs as react components from a folder created by the backend. Additionally, there will be a WAMP (bonefish/autobahn) solution where I will be provided with the name of an icon to use (even though this may see ...

Uploading Files to the Server with Angular 2 and ExpressJS

In my Angular-2 project, I am currently working on uploading files to the server. The code snippet provided below showcases how the file is uploaded: My main question pertains to linking these uploaded files to specific mongodb documents. How can I achiev ...

Reactivity in Angular Autocomplete with API Integration

I went through all the tutorials on Angular Autocomplete using API to follow the steps. I implemented valueChanges to monitor the form control, used switchMap to send a new request with each keyword change, and then displayed the data in the autocomplete d ...

error TS2559: The type 'BookInterface[]' does not share any properties with the type 'BookInterface'

Hello, I am currently working on a project using Angular 7 and encountering the error TS2559: Type 'BookInterface[]' has no properties in common with type 'BookInterface'. Despite making changes to the code, the issue persists. Below is ...

What is the best way to obtain the variable value?

What is the best way to pass a variable to the component sibling1? <parentComponent> <sibling1 [data]="parentData"></sibling1> </parentComponent> ...

Heroku error: unable to locate tsc despite exhaustive troubleshooting efforts

I've been attempting to deploy a basic nodejs app on heroku, but I keep encountering the error mentioned above. Despite trying various solutions provided here, nothing seems to resolve the issue. Here's a summary of what I've attempted so fa ...

Determine the types of values for an object through the use of Generics

After spending a while pondering over this issue, I have yet to discover an elegant solution. My dilemma begins with an Enum: export enum Enum { A, B, C, } Next, there is an object that utilizes the Enum. While the structure is somewhat predi ...

Exploring the benefits of using TypeScript with Angular2 for HTTP

I have a locally stored "region.json" file containing the following data: { "regionId":1, "region":"CAN" }, { "regionId":2, "region":"CEN" } Additionally, I have an "enviroment-app.component.ts" file structured as follows : import {Component, ...

Troubleshooting Challenges with Installing Angular 5, Node.js, and N

I currently have Node and NPM installed with the most recent versions. When attempting to install Angular/cli, I encountered an error message stating: angular/cli and npm versions not compatible with current version of node. I am beginning to think that I ...

Encountering a 404 (Not Found) error while trying to access a null resource in Angular at http://localhost

Currently, I am developing an angular application with ng9. I have a specific div where I need to display an avatar using an image fetched from the API in my component.ts file: .... export class HomeComponent implements OnInit { nextLaunch$: Observabl ...

"Learn how to pass around shared state among reducers in React using hooks, all without the need for Redux

I've built a React hooks application in TypeScript that utilizes multiple reducers and the context API. My goal is to maintain a single error state across all reducers which can be managed through the errorReducer. The issue arises when I try to upd ...

Upgrading Angular causes issues with fileReplacements not functioning properly for assets

Since upgrading Angular, I have encountered an issue where fileReplacements no longer work with assets. Here is the code snippet that I am using: "fileReplacements": [ { "replace": "src/assets/scss/x.scss", ...