I am trying to communicate between one component and another, which are in different views. In the first component there is an input, and what I want to do is that when the submit button is pressed with a written text, a new view is accessed and in the new component, retrieve the text and display it in the new view.
Do you have any idea?
I have tried to do it as it appears here, but it only works for components that are in the same view:
Perhaps the question is too broad, so I can't give you a precise solution, but we will try to clarify ideas. If you have two components in an app that need to share data, the ways to do this vary depending on the relationship between these components:
If one component is the parent of the other
The parent component passes information to the child by declaring its use in the template:
In the parent you will have some attribute declared (let's call it
<app-componente-hijo [entrada]="datos"> </app-componente-hijo>
And in the child you will have declared an input:
The son sends information to the father:
<app-componente-hijo (onDataReceived)="leerDatos($event)"> </app-componente-hijo>
Here the child declares with
@Output()an emitter (
EventEmitter) to which the parent subscribes by passing the function that will process the data.
If the components have a common parent
This case is similar to the previous ones: the parent component can receive/send data from one child to another via input/output
If the components have no relationship beyond being in the same application instance
In this case, it is usual to use a service: one component uses said service to send the data and the other component uses it to receive it (the communication can be bidirectional). The service can keep the data in memory (a variable acts as a temporary buffer) or it can store it somewhere more persistent (localStorage in the browser or it could even send the data to the server).
If the components are in different instances of the application
That is, you have two tabs open with the same application in the same browser . This is the equivalent of having two desktop applications open and trying to communicate two objects from each application: you need something external to the applications, such as the server or localStorage (if you have a service class of type
LocalStorageService , you will have two instances, but share browser memory)