How to build angular 2 component

In this article, I am going to cover how to build simple angular 2 component, what is a component?  components are re-usable modular units which handle specific functionalities, you can build component once and re-use it on multiple places of your application

I am going to use Visual Studio Code IDE to develop Angular 2 component, for more information on IDE, you can refer this article Setting up visual studio ide for angular 2

This example covers simple functionality  which is displaying HTML on the page, for advanced functionality refer my other articles

If you are familiar with any programming language then it is very easy to understand Angular 2 components, here we are using TypeScript which supports class-based object-oriented programming, for our component I am going to define a class called simple component

In Angular 2 every component is a class, to tell Angular 2 that this class is a component, we must define @component directives just above the SimpleComponent class

You need to import the Component directive from the core module

The next thing is we need to define properties selector, styleUrls and templateUrl, the selector defines html tag, you can call this component by using <simple-component></simple-component>

If you have component specific external .css file and  want to call it as part of component then we can use styleUrls property, but you can use also write inline styles in the component something like below

The templateUrl holds the markup of component, this we can consider as a view, we can call external markup by simply assigning to the templateUrl property, we can also write inline markup by using template property something like below

To bootstrap the application we need to call below code in main.ts file

In the index.html file to call a component just use below code

Leave a Reply

Your email address will not be published. Required fields are marked *