Angular - Component Interaction
Sharing Data between Angular Components
Angular provides options to share data from parent component to child component as well as, child to parent component. Also, it is possible to share data between any other component within the Angular application. Component is a TypeScript class decorated with the @Component decorator. It is used to create the user interface.
Data sharing is the practice of making important information accessible to different parts of an application. It is done by transferring data from one component to another, allowing access to data during operations, or synchronizing data between different parts of an application.
Interaction between components is one of the important and necessary features in the context of component based architecture. Angular provides multiple options to pass and receive data between components. Let us see how to share data between components in this tutorial.
How Components Interact in Angular?
In Angular, parent and child components shares data or interacts to each other through the following ways −
- Using @Input decorator
- Using @Output decorator
- Using local variable
- Using @Viewchild decorator
- Using Services
Multiple Choice Questions on Angular Component Interaction
Now that you have learned the how Angular Components interacts, let's test your knowledge. Please answer the following questions based on your understanding −
Q. 1 - Which Angular decorator is used to pass data from a parent component to a child component?
Answer : C
Explanation
The @Input decorator bind data of the parent component to a property in the child component.
Q. 2 - Which lifecycle hook detect changes in input properties in Angular?
Answer : A
Explanation
The ngOnChanges lifecycle hook is called whenever Angular detects changes in the input properties of a component.
Q. 3 - Use of @Output decorator:
A - It allows the parent component to pass data to the child component.
B - It creates an event emitter for the child to send data to the parent.
Answer : B
Explanation
The @Output decorator is used to emit events from the child component to the parent component.