angular

What are Angular 2 Components

Angular 2 consists of a lot of new features and one of the most fantastic features is the ability to create components. In fact Angular 2 is called a component-based framework and is directly inspired by web components.

Web components are the collections of standards that allow us to create reusable UI widgets. These widgets fully encapsulate all their markup and styles and could be easily imported on a page by simple one line import statement. Web components make the html language more expressive. Angular 2 components could be considered as Angular 1 directives that are associated with their own template, i.e.

Angular 2 Component = Angular 1 Directive +  Angular 1 Template

Project Overview

In this tutorial, we will create a very simple Angular 2 component (AppComponent or Parent component). Then we will create another component (Child Component) and we will see how to nest the child component inside the parent component.

After covering the basics of nesting one component inside another component, we will use this approach to create the application below where parent component consists of Author details and child component consists of his books. It’s a fairly simple demo app but should allow us to convey the concepts well.

See the Pen Angular2: Nested Components by Raj Gupta (@rajdgreat007) on CodePen.


 

Project Steps

  • Install and setup dependencies
  • Build Parent Component
  • Build Child Component
  • Nest Child Component

Project Setup

To create Angular 2 project, first we need to set up the environment and do few installations.

Install Node.js, npm and typescript

First we need to download and install node.js. It can be directly downloaded from node.js website. The downloaded package will install both node.js and npm (node package manager). We can check if the installations are successful by simply opening the terminal (cmd for windows) and writing the following commands :

node  -v

If node.js is installed successfully, the above command will output the version of the node.js. Similarly the below command will output the version of npm :

npm  -v

After node.js and npm are successfully installed, we need to install typescript. It can be easily installed by writing the following command in terminal :

sudo npm install -g typescript

The above command will install typescript with the following output :

It is recommended to write code in typescript and using a transpiler that converts typescript code into javascript code. One of the several reasons for using typescript language in Angular 2 is, typescript have in-build support for decorators/annotations which are helpful in creation of web component metadata.

Clone Angular 2 quickstart project from github

After installing node.js, npm and typescript, the next step is to clone Angular 2 quickstart project from angular github repository. This project provides the basic setup and we can start building our components on the top of it. To clone this project, open the terminal and type the following command :

git clone  https://github.com/angular/quickstart  angular-components

It will clone the angular quickstart project into a folder ‘angular-components’.

Next step is to navigate inside the ‘angular-components’ folder by typing the following command:

cd  angular-components

The next step is to install npm packages using the package.json file (included in ‘angular-components’ folder) by typing the following command:

npm install

It will install all the dependencies which are needed for the project including a transpiler to convert typescript files to javascript, a compiler that will keep looking for changes in project files and will recompile as soon as change is detected and lite-server.

Next, type the following command to run the application :

npm  start

This command will compile the application and run lite-server which has already been installed as project dependency. It will also open a new tab/window in web browser and we can see our application running on localhost on port 3000 ( http://localhost:3000 ).

Building the Parent Component

Now, the quickstart project is up and running and so we are all set to create our first component. Actually, the quickstart project already provides an example of a very simple component. If we go to http://localhost:3000, we can see the heading text “My First Angular 2 App”. That text is coming from a component that already exists in quickstart project and its called as AppComponent. We will understand all parts of the component step by step and modify it to create our parent component. The AppComponent exists inside a file called app.component.ts which is located inside ‘app’ folder. The ‘app’ folder is our working directory which consists of typescript (.ts) and javascript (.js) files. If we create a typescript file and write some code into it, it will be automatically transpiled to javascript file and will be saved inside ‘app’ folder.

Let’s understand each line step by step.

Step 1 : Import Component Object

import { Component } from ‘@angular/core’;

Angular 2 uses ES6 style syntax which allows to reuse code by importing them from one file to another.  In the above code, we are importing Component object from @angular/core. @angular/core is included as a dependency in package.json file and thus it was downloaded by npm when we executed npm install command.

Step 2 : Adding meta-data to class

We can add meta-data to our typescript class using the @Component decorator. The meta-data may include the following:

selector: It defines the name of the tag which can be used to add the component in html file. In the quickstart project example, the name of the tag is ‘my-app’ and we are going to use it as such. So, to use this component, we will use the tag <my-app></my-app> in the landing html file which exists in the angular-component folder and it’s called index.html.

styles: It defines the styles (css) associated with the component. It takes an array of inline styles. To specify external css file urls, we can use styleUrls instead of styles. We will use it while customizing the component.

template : It defines the markup associated with the component. It takes a single line or multiline string. We can specify multiline string in typescript by using backtick (`) character. We can also specify an external template by using templateUrl instead of template.

directives : If we want to use one component inside another (nested components), we can do so by specifying the child component in the directives attribute. It takes an array thus allowing us to nest multiple child components inside the parent.

providers :  We can pass the services which are needed by the component using providers.

Step 3 : Export the class

export class AppComponent { }

We need to export the class to make it usable by other parts of the code. After it is exported, it can be simply imported by using the import statement (as in step 1) and can be used. We can also specify variables and functions inside the class which can be used by the component’s template.

After understanding the bits and pieces of the above angular 2 component, we are all set to customize it as per our needs. We will use it as the parent component. We will change the template and will add few style that will be applicable to the component. Below is the modified version of the AppComonent.

Change 1 : Modified template

Added a div with class “parent” and changed the text inside h1 tag to “Parent Component”. We will soon see how to pass this data dynamically from the exported class and access it inside the template.

Change 2 : Added styles property

As mentioned earlier, styles takes an array. Here, we are passing a multiline string as the first element of the array. The multiline string consist of css that will be applied to the component markup specified by template property.

Now if we go to http://localhost:3000, we will see that the page is automatically refreshed and displaying the parent component markup with css specified through styles property applied correctly.

The data contained in h1 tag of the template is hard coded. We can make it dynamic by creating a variable in AppComponent class, assigning the data to that variable and accessing the data in template using double curly braces ({{ }}).

Building the Child Component

The next step is to create the child component. We will create a typescript file named ‘child.component.ts’ inside the ‘app’ folder and add the following code inside it:

The name of the selector is ‘child-component’, which means it can be inserted by using the  tag <child-component></child-component>. It has its own styles and template. There is also a name variable inside the ChildComponent class which is being used inside the template, just like we did for the AppComponent.

Nesting the Child Component Inside Parent Component

At this point, we are done with creating both the components. Now, the final step is to nest the child component inside the parent component. We need to make the following 3 changes inside the app.component.ts file to achieve this :

Step 1 : Import child component

To use a component, first we need to import it. It can be easily done by one line import statement :

import { ChildComponent } from ‘./child.component’;

Here, ChildComponent is the name of the class that we exported from child.component.ts file.

‘./child.component’ specifies the path of the component. We do not need to use the extension (.ts) while writing import statement.

Step 2 : Add the imported component inside the directives property of AppComponent decorator

As mentioned earlier, directives property specifies any child component which we want to use inside the parent component. In the component decorator of AppComponent, we will add the directives property and assign imported child component to it :

directives : [ChildComponent]

Step 3 : Use the Child component tag inside parent component template

The modified parent component template would look like :

<div class=”parent”>

<h1>{{name}}</h1>

<child-component></child-component>

</div>

With the above 3 changes in place, the final version of app.component.ts file will be :

Now, we can navigate to http://localhost:3000 and see the child component nested inside parent component.

Now we are all set to use the above setup to create an Author (Parent Component) and nest his books (Child Component) inside Author.

Let’s open app.component.ts and change it as follows (changes are marked in bold) :

Here we tweaked the template to display Author name and also changed it from inside the class.

Now let’s open child.component.ts and change it as follows (changes are marked in bold) :

Here, we have assigned the array of books to a variable named books in the ChildComponent class. We also changed the template to add books markup. We are using *ngFor (equivalent to ng-repeat of Angular 1) to loop through the array of books and displaying title and price of each book.  We also added css for styling each of the book.

Conclusion

We went through the details of Angular 2 components and use of typescript language to create them. We also went through the attributes of component decorator (selector, styles, template, directives, providers) which are helpful while creating the component. We saw how to create components and finally how to nest child component inside a parent component.

Comments

  • Alina
    Reply

    Hello,

    I followed along with this tutorial, and there are two things that need to be changed in order for the example to work.
    1. ChildComponent needs to be added to declarations in app.module.ts
    2. the ngFor should be using let instead of # : *ngFor=”let book of books”

    Hope this helps others doing this tutorial.

    All the best,

    • Jean Gerald Muyuela

      I hate this.. if you only need specific component or directive in a specific component, then it should only be declare there and will not be available globally… the attribute directives in @Compoment make sense specially its more OOP T_T. having everything in declaration will make it look ugly and less OOP Like…. kinda turns me off.. still no true OOP Web development… my hopes is shattered.. still stuck with this ugly coding….

    • Sameer Argade

      I added it to app.module.ts but I get template parse error is not a known element

  • Mark
    Reply

    Hi there, good read – however it should probably be pointed at somewhere here that this article is referring to the strategy used in an older version of angular2 pre RC.5 (and pre RC altogether for the # instead of let inside ngFor). The link to the angular quickstart to download the code takes you to download the RC.6 version, which is why Alina had to make the changes to the code in order for it to work.

  • Backup Folder
    Reply

    Nice article. However, it’s important to note:
    using of “directives” (directives : [ChildComponent]) is deprecated in RC.6.
    use ngModule declarations: instead.