Hello readers, In this tutorial, i am going to explain you about Components in Angular 2. In my previous session, we have learned  Modules in Angular 2.  Here we are going to see what exactly is Component in Angular 2.

Introduction to Components in Angular 2:

Components are the fundamental building blocks of the Angular 2 application that contains both the logic and Views(UI templates) of an angular 2 application.
A component consists of the following:

  1. Template.
  2. Class.
  3. Metadata.

Template:

This contains the HTML code that needs to be rendered in the application. A template is a view with which the user interacts.

Example of defining Template

Template:'
<h2>My App</h2>'

Class:

The class in Angular 2 component is similar to the class in c, Java, C#. The class is defined in TypeScript.

The syntax for defining Class:

class classname
{
PropertyName:PropertyType=Value
}

Where;

classname is the name of the class.
PropertyName is the name of the property.
PropertyType is the datatype of property.

Value This is the value that needs to the property.

Example:

export class AppComponent
{
appTitle:string:"Hello World";
}

MetaData:

Basically, metadata can be used to describes the component and sets the value for different properties, so that a TypeScript class can be used as an Angular 2 component.

Complete code for component:

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

@Component ({
selector: 'my-app',
template: ` <div>
<h1>{{appTitle}}</h1>
<div>To Debug On Web</div>
</div> `,
})

You can see the component has an attribute called selector called my-app this is custom htm tag which can be used in our html page as follow

<body>
<my-app></my-app>
</body>

View More:

Conclusion:

I hope this session is helpful. I would like to have your feedback, comments, and suggestions.

Thank You.

Leave a Comment