Angular
Building UI Functionality with Angular Components

Nesting Components

PRO

One of the most popular aspects of web frameworks like Angular is the idea of “componentizing” all the various parts of your application. Angular has proven, more than ever, how separating your application into separate components can help improve code management and reuse. Let’s take a look at a very simple example of nesting components and how we can construct this.

For our example, we will be constructing two components that resemble a basic application layout — a main App component and a Header component that is nested within it. We will not go too far into the details since our focus here is more about how nesting components works rather than how to create a fully fledged layout.

app/app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: 'src/app/app.component.html'
})
export class AppComponent {
  constructor() {}
}

And its template is the following:

app/app.component.html

<layout-header></layout-header>

Nested components rule!

You'll notice that we placed an HTML tag called <layout-header> — this is how you nest components in Angular! This tag name should be identical to the selector metadata in the header component itself, otherwise it won't actually place our header component there. Lets take a look:

app/shared/layout/header.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'layout-header',
  templateUrl: 'src/app/shared/layout/header.component.html'
})
export class HeaderComponent {
  constructor() {}

  name: string = 'Angular';
}

And its template:

app/shared/layout/header.component.html

<div>
  <h2>Hello {{name}}</h2>
</div>

As displayed above, you can see that it does not take a whole lot of code to nest components. <layout-header> is our child component and displays an H2, and the AppComponent is the parent component that hosts it.

Now, you may remember that we can't use components until they are declared in a module — this is still true. Lets modify the AppModule to declare the HeaderComponent:

app/app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { HeaderComponent } from './shared/index';

@NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent, HeaderComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}

You can view the working source code here:

And with that, you have successfully nested Angular components!

For more information about Angular components and how to nest them, I suggest visiting this great tutorial by our friends at Google on Nesting Component using Parent/Child components

 

I finished! On to the next chapter