J
J
Jedi2018-12-18 13:47:12
Angular
Jedi, 2018-12-18 13:47:12

How to pass data between components?

Hello!
I want to pass data from one component to another.
HomeComponent's template:

<app-products></app-products>

<app-wishlist></app-wishlist>

products.component.html markup:
<ul>
  <li *ngFor="let item of data" (click)="handleClick($event, item)">{{ item.title }}</li>
</ul>

products.component.ts:
export class ProductsComponent implements OnInit {

  public data = [
    {title: 'lorem ipsum'},
    {title: 'lorem ipsum'},
    {title: 'lorem ipsum'},
    {title: 'lorem ipsum'},
    {title: 'lorem ipsum'},
  ];

  constructor() { }

  ngOnInit() {
  }

  handleClick(event: Event, data) {
    event.preventDefault();
    console.log(data);
  }

}

As you can see, by clicking on each list item, I can get it in products.component.ts.
The question is, how do I pass from products.component.ts to wishlist.component.ts ?
How to implement it correctly?
Give a detailed answer, please. I will be very grateful!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Stolyarov, 2018-12-18
@PHPjedi

Through the service.
1. In the parent component or in the module, register it in providers .
2. Inject into each of the components.
3. In the service, depending on how the wishlist should receive data
a. through RxJS declare Subject and subscribe to it in the wishlist
b. in the wishlist, take data from the service directly (access a specific property or method)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question