Communication between components shown in different views Angular 5

2

I am trying to make communication 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 send 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 ideas?

I have tried to do it as it appears here, but it only applies to components that are in the same view:

link

    
asked by neo 28.06.2018 в 10:21
source

1 answer

0

Maybe the question is too broad, so I can not give you a precise solution, but let's try to clarify ideas. If you have two components in an application that have to share data, the ways to do it 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 when declaring its use in the template:

    In the father you will have some declared attribute (let's call it datos ):

    <app-componente-hijo [entrada]="datos"> </app-componente-hijo>
    

    And in the child you will have an input:

    @Input() entrada;
    
  • The son sends information to the father:

    <app-componente-hijo (onDataReceived)="leerDatos($event)"> </app-componente-hijo>
    

    Here the child declares with @Output() an issuer ( EventEmitter ) to which the parent subscribes by passing the function that will treat the data.

If the components have a common father

This case is similar to the previous ones: the parent component can receive / send data from one child to another through input / output

If the components have no relationship beyond being in the same instance of the application

In this case, the usual thing is to use a service: one component uses this 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 can save them in a more persistent place (localStorage in the browser or could even send the data to the server).

If the components are in different instances of the application

This is the equivalent of having two open desktop applications and trying to communicate two objects of each application: you need something external to the applications, such as the server or the localStorage (if you have a service class of type LocalStorageService , you'll have two instances, but they share the browser's memory)

    
answered by 28.06.2018 / 10:48
source