Angular 2 - Creating Components

Creating a Component

Use the Angular 2 CLI to create components as needed.

In the command line cd to the /src/app directory in your Angular 2 application.

Type the following command: ng gnerate component componentName where componentName is the name of your new component. For demonstration purposes I'll create a new component called "home", so my issued command is
ng gnerate component home

You should see that Angular 2 just generated a new folder with the name of your new component, and it should be sitting in /src/app/home/, and inside of that folder are now the 3 files:


(Yes there are other files generated but the above mentioned files are the main ones, I'll revisit those other files at a later time).

This is important as it continues to support the Angular 2 notion that all other components are nested under the root component (app.component). This is further realized when it comes time to "connect" your new component into your application. The diagram below will help explain what needs to happen in order to "connect" your newly created component into the Angular 2 app.

From the bottom up (since app.component is considered the root (TOP level) component, and all other components reside under the root component...) the newly created home.component.ts file has been created and looks similar to the app.component.ts file; a few different hooks now exist as you can see the constructor method on line 10 and the ngOnIt() method that could include functionality to execute when the new component gets initialized. Notice the selector that was automatically created called "app-home", you'll need this in a minute....

home.component.html and home.component.css are spartan and empty, respectively.

Hooking this new component into your Angular 2 app requires the following steps:
  • In the app.component.ts file you'll have to add an import statement (line 2) for the home component. Also, notice the addition of directives on line 8 which is necessary to tell app.component to use the new home component.
  • In the app.component.html you'll have to add the selector that was generated on line 5 in home.component.ts (app-home) so that the view can display the contents of home.component.
  • In home.component.html you'll simply configure your view to display contents as you wish.


As long as you remember that your new component needs to be injected into the app.component, and not directly into the index.html file - you're on your way to building out your new Angular 2 application.

Link your website to this page! Copy and paste the URL below: