Creating Component in Angular 2

Posted on Updated on

Angular 2 being one of the most advanced front-end framework is lead in UI application development framework. Angular 2 is component driven framework, we are supposed to create components to develop the application. In our previous article Angular 2 Hello world example, we discussed how to create Angular 2 application using angular CLI. Here in this article, we will be discussing about steps to create a component in Angular 2 application.

Note: We are going to create emp component which will be displaying employee first name and last name.

Step 1: Create a folder emp under app folder.

angular 2 folder

Step 2: Create file for EmpComponent

Create a new file emp.component.ts inside emp folder and add below code in it.

Following are the brief description about the code

  1. Line 1 imports Component class from core package of Angular 2 which is mandatory to create a component.
  2. @Component contains three part
    1. selector: defines the name of the HTML tag where this component will live. In this case, our component will by shown through the <emp></emp> tags.
    2. templateURL: defines the file in which we have to write the html template for this component. You can use template in case you want to write html inside same typescript file.
    3. styleUrls: defines files which contains css classes to style the component. One can add multiple css files in one component. You can use styles in case you want to write style class in same typescript file.
  3. Define component class which in our case will be EmpComponent and use export keyword before the class, so that we can import it in app.module.ts and reuse it.
  4. Now we have defined variables firstName & lastName and initialized in the constructor.

Step 3: Create file for html template

Create a new file emp.component.html inside emp folder and add below code in it.

Step 4: Register EmpComponent to app module of the application

Register EmpComponent to the app module and bootstrap it so that we can use this component into our application. app.module.ts code after registering our component to the application.

Step 5: Component is ready to use

Now we are ready to use our component. Open index.html file and add below code.

Step 6: Run the application

Run the application in any of the server, you will get output as

component output

Stay tuned for more updates and tutorials !!!

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.