I am here to continue the discussion around AngularJS 2.0. Today, we will discuss about Component in AngularJS 2. Also, in case you did not have a look at our previous articles of this series, go through the links, mentioned below.
In this article, we will cover the topics about component, as shown below.
- What is component.
- How to create a component.
- About component function properties or argument.
- Life Cycle of the component.
- Nested component.
In my previous article, I discussed how to write a simple "Hello World" type program in Angular2. In that program, we developed a component class named FirstProgComponent with the @component decorator. Actually, component is the main building block of Angular2 Framework. In Angular2 application project, any number of components can be created and used within a single HTML file. Basically, Angular2 framework is a component based framework, which is the main difference from the previous version of AngularJS.
Actually, previous versions of AngularJS are based on the concept of controller and directives to populate the data and also responsible to develop any custom elements for the view but in Angular 2, components perform all the responsibilities that are performed by controllers and directives.
What is component ?
In Angular2, every thing is component. Component is the main building block of Angular2 framework. Basically, component is the main process in which we can define or design the views including the logic.
Steps to create a component
Although, we have already created our first component in the previous article. But in spite of that, I describe the steps for creating a component.
- Create a typescript base class and export it. As it is very much clear from its name that export keyword is used to export any type of objects like class, functions etc. from an angular module. Export is basically just an identifier, which indicates that it can be import into any other script section, using import keyword or module in Angular2. Export or import both the modules are supported by ES6 module definitions.
- Now, decorate the class with @component metadata decorator or annotations. Basically @component add some metadata to the class objects in order to provide some specific meaning. Basically, it is the declarative way to add metadata to the code.
Now, the first questions arise that where the @component is defined? As we all know, it is not a JavaScript keyword or method. The answer is that this keyword is provided by Angular2 framework itself. Basically Angular2 framework provides us some inbuild module or provider for the perform our task. For use @component decorator or annotation in our class, we need to import the
code module into our class file at the beginning.
import {component} from ‘@angular/core’
- Import the required library or module to develop the component.
- Now, include the component class within the ngModule in order it to be used by other component or Applications. To mention that component is a member of ngModule, you need to add the component name within the declaration field of ngModule.
Component Configuration
@Component decorator basically decorated a type script class as a component objects. Basically, it is a function, which takes different types of parameters. In the @component decorator, we can set the values of different properties to finalize the behavior of the components. The most used properties are shown below.
- selector
A component can be used by the selector expression.
- template
Basically, template is the part of the component, which is rendered in the Browser. We can directly define HTML tags or code within the template properties. Sometimes we called this as an inline template. For writing multiple lines of HTML code, all code need to be covered within tilt (`) symbol.
- templateUrl
Another way of rendered HTML tags in the Browser. Here, we need to provide the HTML file name with its related file path. Some times, it is known as external template. It is better approach, if HTML is a part of the component is complex.
- moduleId
It is used to resolve the related path of the template URL or style URL for the component objects.
- styles or stylesUrls
Component can use its own style by providing custom CSS or can refer to an external style sheet files, which can be used by multiple components at a time. For proving inline style, we need to use styles and to provide external file path or URL, we need to use styleUrl's.
- providers
We are in the real life Application. We need to use or inject different types of custom Service within the component to implement the business logic for the component. To use any custom Service within the component, we need to provide the Service instance within the provider. Basically, provider is an array type property, where multiple Service instance name can be provided by comma separation.
Life Cycles of the Component
The life cycle of the component is maintained by Angular2 himself. Below is the list of life cycle method of Angular2 components.
- constructor
This method is executed before the execution of any one life cycle method. It is basically used for inject dependency.
- ngOnChanges
This method is called when an input control or binding value changes.
- ngOnInit
This method is called after the execution of first ngOnChnages.
- ngDoCheck
This method is called after every execution of ngOnChnages.
- ngAfterContentInit
This method executes after component content is initialized.
- ngAfterContentChecked
This method is executed after every check of the component check.
- ngAfterViewInit
This method executes after component views initialize.
- ngAfterViewChecked
This method executes after every check of component views.
- ngOnDestroy
This method executes before the component destroys.
Now, to create a component, first create a typescript file named app.component.template.ts and add the code, mentioned within it.
- import {
- Component
- } from '@angular/core';
- @Component({
- moduleId: module.id,
- selector: 'hello-world',
- templateUrl: 'app.component.template.html',
- styles: ['h1{color:red}']
- })
- export class TemplateComponent {
- message: string = "Angular 2 Component with Template";
- author: string = "Debasis Saha";
- constructor() {}
- }
In the code, mentioned above, I use template URL and style to show the text in different color. Now, for template HTML file, add HTML file named app.component.template.HTML and add the code, mentioned below.
- <div>
- <h1>{{message}}</h1> <br />
- <h2>{{author}}</h2>
- </div>
Now, run the code and the output is mentioned below.
In the example, mentioned above, I set the color of h1 tag as Red. Thus, when I run the code in the Browser, it will effect automatically. The same thing can be done by providing the style code within a CSS file and provide the file name with the relative file path to import the style class into the document.
Nested Component
Just like previous version of AngularJS, Angular2 also allows us to create nested component or component inside a component.
Let's see how it works. I first create a component called parentcomponent. Now, I also create two separate components named childComponent and EmailBoxComponent. Now, I want to use these two components within the parent component template. For doing this, I need to do the following.
- Import childcomponent and EmailBoxComponent within ngModule.
- Include the component name within declaration property of the ngmodule.
- Use child component, using their selector in the parent component template.
To demonstrate the nested component, I first create two child components. One of them simply displays some fixed text message within h2 tag. The another child component will be a simple search button with textbox. For doing this, we need to add one TypeScript file named as "app.component.child.ts" and write down the code, mentioned below.
- import {
- Component
- } from '@angular/core';
- @Component({
- selector: 'child',
- template: '<h2>{{message}}</h3>'
- })
- export class ChildComponent {
- message: string = "This is Child Component";
- constructor() {}
- }
Now, add another TypeScript file with name "app.component.emailbox.ts" and write down the code, mentioned below.
- import {
- Component
- } from '@angular/core';
- @Component({
- selector: 'email-box',
- template: '<input placeholder="Email"/><button class="btn-clear">Register</button>'
- })
- export class EmailBoxComponent {}
Now, create another TypeScript file named as "app.component.parent.ts" and add the code, mentioned below.
-
- import {
- Component,
- OnInit
- } from '@angular/core';
-
- @Component({
- moduleId: module.id,
- selector: 'my-app',
- templateUrl: 'app.component.parent.html',
- })
- export class ParentComponent implements OnInit {
- constructor() {}
- ngOnInit() {}
- }
Now, create another HTML file named as "app.component.parent.html" and the add the code, mentioned below.
- <div>
- <h1>This is Main Component</h1> <br />
- <child></child>
- <child></child>
- <child></child> <br />
- <email-box></email-box>
- </div>
Now, add another TypeScript file for module with name "app.module.ts" and write down the code, mentioned below.
import { - NgModule
- } from '@angular/core';
- import {
- BrowserModule
- } from '@angular/platform-browser';
- import {
- ParentComponent
- } from './src/app.component.parent';
- import {
- ChildComponent
- } from './src/app.component.child';
- import {
- EmailBoxComponent
- } from './src/app.component.emailbox';
- @NgModule({
- imports: [BrowserModule],
- declarations: [ParentComponent, ChildComponent, EmailBoxComponent],
- bootstrap: [ParentComponent]
- })
- export class AppModule {}