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:
- Application Data
- 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.
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 2 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 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.