Updated March 20, 2023
Introduction to Angular 2 Component
The following article provides an outline for Angular 2 Components. Angular 2 is divided into subparts or small parts to make the structure of application easier. It is very much different from the previous version of angular. Angular components are the part of the module or we can say that module contains components that implement the business logic of the application and also they contain the templet which is going to trigger when they invoked.
So angular application can have any number of component it is the main building block for the application which contain the view and the business logic. Angular 2 component acts as a controller between view and business logic. Hence we can say that any custom element, data or logic can be created or added or display by the use of components in angular 2.
So it contains the main thing for an application like:
- Services
- Template
- Business Logic
- Styles and CSS
- Application data
Explanation of Angular 2 Components
Now we can have a closer look at how this component work and what type of metadata it contains. we have to follow some steps to create a component in angular 2.
Step 1: Create a class annotated with @Component annotation. In this, we set various metadata properties so that this class can be identified as an angular 2 component.
Step 2: Export this class. This will contain the business logic and server calls to get data. It will also contain angular 2 in the build method which will automatically get invoke during the life cycle of the angular component.
Step 3: We may require the different libraries and other components, in order to use them we need to import them by specifying their path.
Create an Angular 2 Component
We can have one example of how we can create our first Angular 2 component.
Example
import { Component, Inject, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'] ,
providers: [BookService]
})
export class AppComponent implements OnInit{
displayedColumns: string[] = ['name', 'price', 'symbol'];
private object: any = {};
private dataSource: any[] = new Array<any>();
constructor() {}
ngOnInit() {
consoloe.log("component invoked.");
}
}
As we have above example in which we have to define the path from which we are importing the @Component annotation which is available in @angular/core library.
Here we have also used OnInit interface which provides ngOnInit() method, this method can be used to load any data which require at the time of page load.
1. Constructor()
It is used to create an object of services or any custom component. We can use this to write our own logic which we want to execute very first.
@Component annotation contains many metadata properties inside it lets discuss them one by one :
- selector: It is the name of the component. It should be unique throughout the application, two angular components cannot have the same name as the selector. Because we use this selector to render our view to the user. then our HTML methods and functions invoke our business logic on events.
- templateUrl: This templateUrl is nothing but the HTML page. Here we need to provide the correct path of our HTML page otherwise it will give as an error. We can only have one HTML page at one time.
- styleUrls: This styleUrls are the array of CSS. In which we can have any number of CSS inside it. But again here path has been correct.
- Providers: These providers are optional, basically it depends upon the business requirement whether we want to call any service in the current component or not. This is the injectable class in angular 2.
so this class will contain the business logic. Our templateUrl and styleUrls are responsible to display the view to the user and display data. Lastly, we have metadata which defines the behavior of the component.
Now component uses different kinds of binding to interact with the view.
a. Interpolation: It is used to display a component property to a template or view. For this, we use double curly braces. We can display anything using this i.e. string, number, array, etc.
syntax:
{{ your_property_name }}
class AppComponent
{
name: string;
object: any;
}
{{ name }}
{{ object.roll_number }}
b. Property Binding: Property binding allows us to directly access the element property of HTML. We can directly assign our variable to an HTML element.
Example
[value]="demo"
Here we are directly assigning demo to value using property binding.
c. Event Binding: This binding uses the event to bind value. We have various events available for instance click.
(click) = "methodName($event)"
It uses parenthesis followed by the function name you want to invoke. In the invoked function we can write our logic.
d. Two-way Binding: This is basically a combination of property binding and event binding. In which we can simultaneously call our method and bind value to the element property.
Example
<input [(ngModel)]="username">
<p>Hello {{username}}!</p>
2. Component Decorator
This decorator decorates the class as a component. By which angular identified it that this is the component. This decorator takes values of different properties and sets their value and decides the behavior of a component. The most commonly used properties are as follows :
- StyleUrls
- TemplateUrl
- Directives
- Selector
- Styles
- Pipes
- Template
- Providers
We also have other properties that are described as follows. We can also have an inline template and an external template.
Let’s take a look through examples.
Examples
Below are mentioned the examples:
1. Inline template
@Component({
selector: "app-root",
template:`
<h1>{{ message}}</h1>
`,
styles:["h1{color:red}"]
})
2. External Template
@Component({
selector: "app-root",
templateUrl: '/app/demo/demo.component.html',
styles:["h1{color:red}"]
})
Also, we have styleUrls and style array for inline and external CSS.
3. Style Example
In this, we are applying CSS internally without using any path.
@Component({
selector: "app-root",
template:`
<h1>{{ message}}</h1>
`,
styles:["h1{color:red}"],
})
4. StyleUrls Example
Here we are providing a path for the CSS file to load it from external.
@Component({
selector: "app-root",
template:`
<h1>{{ message}}</h1>
`,
styleUrls:['app.component.css','./app/demo.css']
})
Conclusion
So to make any typescript file an angular component we need to use @Component decorator to make it available. Also, it provides value to its different properties.
Recommended Articles
This has been a guide to Angular 2 Components. Here we have discussed basic concept, how to create angular 2 components in detail with respective examples. You may also have a look at the following articles to learn more –