Creating A Nested Component In Angular 4

In this tutorial, we will be looking at how to create nested components in Angular4. There may be a need of separating our component templates and reuse them in other components. So, what we will do basically is to modify our component template and insert the desired components.

The first step is to create a new component by running the following command.

  1. ng generate component servers or ng g c servers  

Note - Servers will be the name of the new component.

 

The command generates the component folder for us which contains the component styling, the template, test section and the typescript file.

So, we have an existing component where we display a simple html tag in it’s template file.

  1. <p>The Server Component and it will be nested </p>  

In order to make use of another component’s template as the template of our newly created component, we will change our component’s template from the component decorator to point to an external template.

 

To something like this.

You should notice that the component template from

  1. templateUrl: './servers.component.html'  

to

  1. template: '<app-server></app-server>'  

this will make the component to use app-server component’s template for our app-server’s template and the beauty of it is that it can be reused. For example, using the component more than once will generate more of the templates.

  1. template: '<app-server></app-server><app-server></app-server>'  
the result will be.


You can also nest components using the inline method.

  1. templateUrl: './servers.component.html'  

Then, insert the app-server component inside the HTML component by modifying the servers.component.html

  1. <app-server></app-server>  
  2.  <app-server></app-server>  

This above example will achieve the same thing. 

Have fun learning Angular4. It's amazing to write my first blog post on a community platform.  
 
Feel free to share with your friends. 
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now