InterviewSolution
| 1. |
What are the different ways that two components can communicate with each other? |
|
Answer» Two components in Angular need to have a parent-child relationship if they WANT to communicate directly with each other. In some cases, having a common parent for two components is also a solution to allow the two child components to be able to communicate. Commonly the following two methods are used.
The second method can be used to perform communication between any two components in the app. They do not need to share a parent-child relationship. They use a service (which is a singleton CLASS) to send and receive data from each other. Services are singleton classes that are instantiated only once throughout the LIFECYCLE of the application. Since these classes can only be instantiated once, there can only be one instance alive at all times. We can use this to share data between components. We can set the VALUES of data members in the service class from one component and can access the values of those data members from other components. Since both the components classes are accessing the only instance, it results in sharing of the information between components. |
|