简体   繁体   中英

Angular 8 Send Data between sibling components

I'm using Angular 8. I have two components which are independant. Form the first one I can click on a button to acces the second one. The both components are not on the screen on the same time, when the second opens we don't see the first. Under the button I use a route with routerLink to access to the second component. My first component is a form and there is a field with an ID. I would like to pass this ID value from the first component to the second when I click on the button but I don't know how to do this. How can I do this? Thanks in advance for your help.

If you look at the Angular Documentation , you'll find that there are several ways to share data between components. However, in this case, the most appropriate way is to use a shared service to coordinate the shared state between components. The service will be created outside of both components and injected into them. The service lifetime will be the same as the application, whereas components may be created and destroyed multiple times and are not designed to hold state for any length of time.

See this article for details on how to make a shared service.

First you need to inject a service Router inthe constructor of your first component as below.

constructor(private router: Router) { }

Then on redirection of your routerlink you can pass the id to second component as below:

this.router.navigate(['/second-component', Id]);

you can import Router as below:

import { Router } from '@angular/router';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM