0

I have a json response and want to pass it from one component to another, both are siblings, both have different html.

Response which I'm getting from the service created which calls APIs. and I don't want to call API two times from two different components. Is it possible to pass data got from one component to another?

How Can I do this?

Avisek Chakraborty
  • 8,229
  • 10
  • 48
  • 76
Nikhil Radadiya
  • 1,995
  • 2
  • 20
  • 43
  • 2
    One way would be to use an Angular service that the two components use to talk to each other. Here in the official docs is a good explanation of how components can talk in general: https://angular.io/guide/component-interaction – Rob Zuber Jun 28 '17 at 11:32
  • @RobZuber both components are not parent-child components – Nikhil Radadiya Jun 28 '17 at 11:33
  • May be this answer will solve your problem. you can refer it from https://stackoverflow.com/questions/34088209/how-to-pass-object-from-one-component-to-another-in-angular-2 – Nilesh Khisadiya Jun 28 '17 at 12:18
  • You can find solution with example from this link https://stackoverflow.com/questions/33966692/how-to-do-inter-communication-between-a-master-and-detail-component-in-angular2/33967426#33967426 – Nilesh Khisadiya Jun 28 '17 at 12:24

1 Answers1

0

If you want to pass data from component-a to component-b and they are siblings, you can do this:

<component-a #compA ></component-a>
<component-b [data]="compA.someData"></component-b>

// Component A:

@Component({
    selector: 'component-a',
    template: '<div>{{ someData }}</div>'
})
export class ComponentA {
    someData: string = "Data from component A"; 
}

// Component B:

@Component({
    selector: 'component-b',
    template: '<div>{{ data }}</div>'
})
export class ComponentB {
    @Input() data; 
}

someData is the data you want to pass from component-a to component-b

Faly
  • 13,291
  • 2
  • 19
  • 37