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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
- Create a class and export it. This class will contain data and the logic.
- 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.
- Import the required libraries and modules to create the component.
Three steps discussed above can be visualized in the diagram below:
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.
Leave a Reply