Introduction to Angular Components

A component is a main building block of an Angular  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 , 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 .

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

 


import { Component } from '@angular/core';
@Component({
selector: 'app-container',
template: `<h1>{{message}}</h1>`
})
export class AppComponent {
message : string = "Hello World";
constructor() {
}
}

 

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  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  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

One response to “Introduction to Angular Components”

  1. […] Introduction to Angular 2 Components and How to print or enumerate properties of a JavaScript object? and How to create constants in JavaScript? (Dhananjay Kumar) […]

Leave a comment

Create a website or blog at WordPress.com