Angular — How to display one component within another.

Linda Ojo
2 min readApr 15, 2020
Angular project

Before we get started, all of the code for this tutorial can be found in my GitHub Repository.

Let's begin with an Angular project which has a container component. We are going to display another component (let's call it child component) within the container component in this post.

We will be using the Angular CLI to generate modules and components, you can install Angular CLI by running the command below.

npm i @angular/cli

Create a Child Component

The first thing is to create the “child” component you plan to display. If you haven’t created the child component already, you can do so using the command below. We will display this child component within the container component.

ng generate component <child-component-name> 

Create the Child module

Navigate into your child component folder and create a module for your component using the command below. The module acts as a package which contains the component and carries everything that concerns the component.

ng generate module <child-component-name> --flat

--flat is a command-line flag that ensures that the module is not created within a new folder.

Open child.module.ts file and import the child component using JavaScript import at the top of the file.

Note: Always import your component or modules using JavaScript before using them in the NgModule decorator.

Next, declare and export your child component within the NgModule in child.module.ts so it's made available to other components including the container component. child.module.ts should look a lot like this 👇🏾

child.module.ts

Import Child Module into Container Module

Next, head on to cointainer.module.ts and import the child Module within the NgModule.

Hint: you can create a container module same way we made the child module if it doesn’t exist. This is what my container.module.ts looks like.

container.module.ts

Display Child Component in Container Component using selector

This is the easiest part. Open container.component.html and display the child component using its selector as shown below. You can find the selector within the @Component Decorator in child.component.ts

<h1>I am a Container </h1><app-child></app-child> //child component selector

That’s all.

Thanks Feranmi Akinlade for reviewing drafts.

Song Recommendation: Work by Charlotte Day Wilson. Check it out on Spotify or Apple

If you have any questions or suggestions feel free to leave a response or reach me on Twitter

--

--

Linda Ojo

I am a frontend developer who is focused on creating functional and beautiful products.