Angular — Nested Components

Jawadhasan
6 min readJun 8, 2023
Photo by frank mckenna on Unsplash

Introduction

Components are building blocks of angular applications.

Splitting the functionality in smaller components is something very common in angular applications development.

In this post we will learn about nested components and discover how to establish communication between nested component and its container component using two useful angular directives @Input and @Output.

We’ll be using the same code-base from the earlier posts and adding more components to it.

Component Usage

Components are typically used in following two ways.

  • As a Routing Target: It appears to the user they’ve navigated to another view. Template is displayed in a full page style
  • As a directive ==> Custom HTML syntax (aka selector). This is same for nested components.

Following picture shows how a child (DeviceCard) component is placed inside a Parent (Devices) component:

When components have such relationship, we can establish communication using @Input and @Output directives.

  • Pass data to a nested-component using @Input.
  • Receive an Event from nested-component using @Output.

Passing Data to a Nested Component with @Input

@Input() decorator marks a field as an input:

It is basically saying that, for this field, data will be coming from parent. It receives the data before calling the ngOnInit() method, so we can use it in ngOnInit() method.

The following picture shows how this nesting is implemented:

--

--

Jawadhasan

Software Solutions Team Lead | Cloud Architect | Solutions Architect