0

When i click on a particular card it is routing to another component but i want along with the data of that particular card should also pass to the another component. Here is the stackblitz DEMO.

Empty_Soul
  • 799
  • 2
  • 13
  • 31
  • please check forked stackblitz solution https://stackblitz.com/edit/angular-movie-read-load-json-sample-eg-d23g6g – TheParam Jan 30 '19 at 10:13

3 Answers3

1

You can achieve solution using shared service

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

@Injectable()
export class DataService {

  selectedCard;
  constructor() { }

  public setSelectedCard(data) {
    this.selectedCard = data;
  }

  public getSelectedCard() : any {
    return this.selectedCard;
  }

}

home.component.ts

import { Component, OnInit } from '@angular/core';
import { DataService} from '../data.service'

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

  contact
  constructor(private dataService: DataService) { }

  ngOnInit() {

    this.contact = this.dataService.getSelectedCard();
  }

}

list.component.ts

export class ListComponent implements OnInit {
  contacts = [];
  constructor(private myService: ContactService, private router : Router, private dataService: DataService) {}

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

  onCardClick(index) {

    this.dataService.setSelectedCard(this.contacts[index]);
    this.router.navigate(['/home']);
  }

}

list.component.html Call the onCardClick() with index

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

Here is forked stackblitz solution

TheParam
  • 10,113
  • 4
  • 40
  • 51
0

The only way is to share via a shared service using setters and getters or observables.

  1. Create a shared service
  2. On click of the card, set the data in the service
  3. On navigating to the router component, read it from shared service by getter or by subscribing to observable

If it is only ID you can pass it using path param or query param. But you should restrict yourself from passing more params via URL.

SharedService

export class SharedService {
  public $cardDataSubject;

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

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

And in child component you can subscribe

constructor(private sharedService: SharedServic) {
    this.$cardDataSubject.subscribe(cardDetails => this.cardDetails = cardDetails);
}
Rakesh Makluri
  • 647
  • 4
  • 10
0

This anwser has found a solution at this link: How do I pass data to Angular routed components?

Top Solution: use 3rd approach by using a service.