Working with Nested Components

What are Nested/Child components?

A Component in Angular can have child components. Also, those child components can have their own further child components. Angular seamlessly supports nested components.

As an example, consider a calculator as a top level component. It is built with several other child components like screen component, button component, body component, battery component etc. These screen, button, body and battery components are nested components of Calculator component.

The nested component have all the functionalities just as any other Angular component. Now several question arises in our mind:

How we are going to use our nested components in its parent component?

How we can pass data from parent component into its child component?

How can we get the data back from child component to parent component?

How does the child component can respond to the parent events?

How does the parent component can respond to the child events?

To answer all these questions, lets us built a step-by-step example where we have a profile page of a person. It will also have a friend's list.

1) Building Parent and Child components.

Let's first built our Child component in our example app which is Friend list component.

Here, we have imported Output and EventEmitter from Angular core library. Also, we have defined an event using @Output() decorator. The OnClick is a local function which is invoked from button's click event. Since the "pingClicked" is decorated with @Output(), it's emit function is able to notify the parent component.

Now, change the parent component to capture the raised event from it's child component as below:

Finally, we have added an Event binding (please check our previous article in Angular 5 : Data & Event bindings) which is "pingClicked". Have you remember, this was decorated with @Output in our child component. Yes, this is how was are able to use it here. Also, it is assigned to a function "onFriendPingClicked($event)". The $event contains the data that the child component emits on the occurrence of it's event.

To Summarize:

Use @Input() decorator to pass data to child component.

Use @Output() decorator to raise an event to parent component. Note : The @Output() decorator property can be only of EventEmitter type.