Passing Data From Parent to Child Component
Explore how to pass data from a parent component to a child component in Angular. Understand the use of property binding in the parent and input binding with the @Input decorator in the child. Learn why storing data in the parent improves reusability and data sharing among components, and discover how to implement property aliases to manage property naming conflicts.
We'll cover the following...
We’ve created our first component. It’s time to make it dynamic by having it load data. First, we must decide where we’re going to define the data.
Storing data
There are two possible locations in which we can define the data: the post component or the app component. The best approach is to store the data in the parent component. It’s common practice to store data at the highest level possible.
There are a couple of reasons for doing so.
First, it allows the post component to remain reusable. If we stored data in the post component, then we’d have the same data in every instance of the component. We want to be able to output the post component with different data each time. Therefore, it’s better to store the data in the app component and pass it down to the post component. The post component will take the data and output it in the correct locations of the template.
Second, it allows us to share the same data with multiple components. In some cases, you will need to distribute data to numerous components. It’s easier to distribute data when it’s stored in the root component.
Let’s update the ...