A component is a main building block of an Angular 2 application, and an application may have any number of components. We can consider a component a particular view of the application with its own logic and data.

In AngularJS 1.0, there was the concept of controllers, $Scope, and directives to bind data and logic to the view or to create custom elements on the view. In Angular 2, components perform all the tasks that were performed by controllers, scopes and directives. Data, logic and custom elements can all be created or added to the page using components in Angular 2.

Angular 2 applications are built around components, and we can consider component as a view with its own:

  • Template
  • Application Data
  • Logic
  • Styles, and more

Let’s Create Our First Component

Let us start with creating a very simple component to display “Hello World” on the page.

appcomponent.component.ts

 

There are mainly three steps to create a component

  1. Create a class and export it. This class will contain data and the logic.
  2. Decorate the class with @component metadata. Basically, metadata describes the component and sets the value for different properties, so that a TypeScript class can be used as an Angular 2 component.
  3. Import the required libraries and modules to create the component.

Three steps discussed above can be visualized in the diagram below:

image

As you can see, the Angular 2 component consists of:

  • A TypeScript Class to hold data and the logic;
  • HTML template and styles to display data in the app. It is also called as a view, which is seen by the user on the screen to interact.
  • Metadata which defines the behavior of a component. Component metadata is applied to the class using the @Component decorator. Different behavior of the component can be passed as properties of the object, which is and input parameter of the @Component decorator.

Read full article on the Infragistics blog

Advertisements

One thought on “Introduction to Angular 2 Components

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s