Learn Angular 4.0 In 10 Days - Component - Day Two

In the previous article, we already discussed the Angular Framework and why it is required, along with the benefits of Angular. Now, in this article, we will discuss Components, the main building blocks of the Angular 4.0 Framework. If you want to read the previous articles of this series, do visit the below link.  

Angular 4 is basically a component-based framework. Components combine concepts that we are already familiar with from AngularJS. The Angular 4 Component combines an AngularJS Directive, Controller, and Scope. Angular 4 is actually component-based MVC Framework. Components are the main building blocks of Angular 4 applications. But before discussing components, first, we need to understand what a component is and why a component-based framework was introduced by Google in Angular.

Component
 
A component is basically a class that is defined to visualize any element on the screen. The components have some properties and by using them, we can manipulate how the element should look and behave on the screen. We can create, deploy, and update our own component as per our requirement. But when writing code using TypeScript, a component is basically a TypeScript class decorated with @Component() decorator.
  1. import {Component} from "@angular/core";  
  2. @Component({  
  3.      selector: 'first-prog',  
  4.      template: 'Welcome to Angular 4.0 Series'  
  5. })  
  6. export class FirstProgComponent{  
  7. }  

Decorators are the JavaScript functions which amend the decorated class in some way. Basically, in these functions, an additional meaning to a plain JavaScript class based on the decorator is used. From the developers' point of view, we just declaratively decorate a class by passing a mandatory configuration object as a parameter to the decorator function. The key idea behind developing an Angular 4 application is to coming up with components and composing them together as required to build an application.

A component is an independent complete block of code which has the required logic, view, and data as one unit. Logically, every component in Angular 4 acts as an MVC concept itself.

Components are a really neat idea. Each component class being an independent unit is highly reusable and can be maintained without messing up with other components. Scaling is as easy as adding more components to your existing application.

Advantages of the Component-Based Framework

As per the current IT leaders, component-based UI development is the future of the web development. Basically, it’s a technique which digital applications need to implement right now. Development work with the help of component-based technique creates a sustainable technical architecture with saving time and costing. Below are the main advantages of the component-based architecture –

  1. Reusability
    In a component-based framework, a component is the most granular unit in our development work and development with components allows for their reuse in future development cycles. Since technology is invaluable because it changes or updates every day, if we develop an application in a component-based format, we are able to swap the best components in and out. One of the challenges of reuse with other development types is that either they are not internally built or they include many dependencies. A component-based UI approach allows your application architecture to stay up-to-date over time instead of rebuilding it from scratch. You can build multiple applications that adhere to the intended design principles.

  2. A component-based UI Approach Accelerate Development Speed
    A component-based development always supports agile development. Components can be stored in a library from which the team can access, integrate, and modify them throughout the development process. Suppose that we were developing a financial application and it required a listing of positions by bank transaction class. So, we can pull a date-wise-bank-transaction-class grid component from the component library and quickly integrate it into the application. The developer does not have to worry about the service signature and creating the logic for the table. In the design process, instead of designing new components, the designer focuses on extending the existing components and designing new components where required. This optimizes the design process without designing a new grid, layout, or navigation. Ultimately, this expedites the design and development process because of the level of reuse.

  3. It Provide Consistent User Experience throughout the Application
    One of the main challenges for an organization is ensuring that the entire application must provide consistent user experience and interactions. The component library acts as a point of governance for the business, designers, and quality assurance teams. In the case of Quality Assurance (QA), teams often have challenges validating the user interface due to a lack of an approved set of user interface standards. The component-based approach enables the creation of a library that provides that approved reference point. This enables the QA team to govern the compliance with UI standards across applications. It acts as a dynamic repository that the QA team can use to validate their tests. As an example, there are many ways to handle a file upload feature within an application. A new application may select an approach that is different from the approved version within the component library; QA can utilize the component library to confirm alignment and then open a UI related defect.

  4. Easy Integration in Development Process
    As components are created or developed by the development team, so production quality UI code can be managed within a centralized code repository. Application development teams are well-versed in using source code repositories, so they are able to extract the code as needed and incorporate it into the application. Leveraging the initial component as a starting point, development teams can extend it to meet their needs. Then, they can submit it to the code repository for review and approval for inclusion.

  5. Component-Based UI development optimizes the requirements and design process
    Using component-based library as a reference, product managers, business analysists, and user experience designers or UI developer can spend less time on defining and details application functionality and user operations. As they work through the definition process and requirements elaboration, they can reference a component as the baseline for the requirement, and then only spend time defining the required extensions and business logic. This minimizes the team’s focus on how specific user interactions should work. Some examples are - filtering, pagination in grids, and displaying of complex data (positions, trades, exceptions). Below are the steps of the development process using the component-based framework.

    1. Requirement Definition – Components are identified during requirement or design process and gaps understood.
    2. UI Design Optimization – UI effort focused on extending existing components and defining new as needed.
    3. Source Code Reuse – Developers first look at the component library before developing a component.
    4. Governance and Quality - Used for governance to ensure alignment and identify any deviation easily.
    5. Integrated with QA – Testing team leverage UI library to validate standards compliance and accelerate the validation process.
    6. Integrated with Development - Generated from application source code and part of the continuous integration/build process.

  6. It speeds up from design to development
    As the rate of change within businesses continues to accelerate, teams need to find ways to accelerate the “Time to Value” for application development projects. Shifting to a design approach that demonstrates the user experience in the browser will have a significant impact on delivery timelines. There is often the issue of “lost in translation” that occurs when a wireframe or visual design is handed over to a development team for implementation. During the process of turning that into the application user interface, issues are surfaced and some portions are not translated correctly. This results in a misalignment of the delivered experience to the defined user experience.
Component Configuration

@Component decorator basically decorates a TypeScript class as a component object. 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 as below. 

  1. Selector: A component can be used by the selector expression.

  2. Template: Basically, a template is the part of the component which rendered in the browser. We can directly define the 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 needs to be covered within tilt (`) symbol.

  3. TemplateUrl: Another way of rendering HTML tags in the browser. Here, we need to provide the HTML file name with its related file path. Sometimes, it is known as the external template. It is a better approach if the HTML part of the component is complex.

  4. ModuleId: It is used to resolve the related path of template URL or style URL for the component objects.

  5. Styles or stylesUrls: Component can be used in its own style by providing custom CSS or can refer to an external style sheet file which can be used by multiple components at a time. For proving inline style, we need to use styles and for providing external file path or URL, we need to use styleUrls.

  6. Providers - In the real-life application, we need to use or inject different types of custom service within the component for implement the business logic for the component. For using any custom service within the component, we need to provide the service instance within the provider. Basically, the provider is an array type property where multiple service instance names can be provided by comma separation. 
 Lifecycle of the Component

The lifecycle of the component is maintained by the Angular 4 itself. Below is the list of lifecycle methods of Angular 2 components.

constructor – method is executed before the execution of any lifecycle method. It is basically used for injecting dependency.
  • ngOnChanges – method called when an input control or binding value changes
  • ngOnInit - method called after the execution of first ngOnChnages
  • ngDoCheck – method called after every execution of ngOnChnages
  • ngAfterContentInit – method execute after component content initialized
  • ngAfterContentChecked – method execute after every check of component check
  • ngAfterViewInit – method execute after component views initialize
  • ngAfterViewChecked – method execute after every check of component views
  • ngOnDestroy – method executes before the component destroys.
Angular Component Architecture Layout

If we remember the Angular architecture, every UI in angular framework must be composed as a tree of Angular Component – one component will be placed beside another component, both of which may be wrapped up by one outer component and so on. This hierarchy starts with one Root Component which is normally called as Bootstrapped Component. Here are the steps of the Create Root Component,

  • Create Angular Module
  • Create Angular Component
  • Add Component to Module
  • Bootstrap Module
  • Bootstrap Component
Create Angular Module

As we already discussed earlier that everything in Angular 4 belongs to an Angular Module, for developing the root component, we first need to declare our first Angular module. An Angular module can be defined by creating a TypeScript class decorated with the “NgModule” decorator. Actually, NgModule is a decorator defined within the “@angular/core” library. @NgModule takes a metadata object that tells Angular how to compile and run module code. It identifies the module's own components, directives, and pipes, making some of them public so external components can use them. In order to use it, we first need to import it as follows,
  1. import { NgModule } from '@angular/core';  
  2. @NgModule()  
  3. export class SampleModule { }  
Create Angular Component

Finally, we reach a position where we need to create our first component using Angular 4. It can be done by creating a class decorated with @Component decorator which defined within the “@angular/core” library. Below the sample code for the angular component,

  1. import { Component } from "@angular/core";  
  2.   
  3. @Component({  
  4.     selector: "home",  
  5.     template: "<strong>Welcome To Angular 4 Series</strong> "  
  6. })  
  7.   
  8. export class HomeComponent {  
  9.     constructor() {  
  10.     }  
  11. }  

In the above code, we pass two parameters to the component decorator,

  1. selector – a simple text representing the tag name of the component.
  2. template – UI part of the component
Add Component to Module

Now, the next step is to add the component within the angular module. It can be done using “declarations” option within “NgModule” decorator. For adding the component, we need to import the component within the module by using import keyword.

  1. import { NgModule } from '@angular/core';  
  2. import { HomeComponent } from './SampleCode/app.component.home';  
  3.   
  4. @NgModule({  
  5.     declarations: [HomeComponent]  
  6. })  
  7.   
  8. export class SampleModule { }  
Bootstrap the Module

As we already discussed, a single angular application can contain more than one Angular modules. But out of the all modules, only one module can be bootstrapped at the beginning. In Angular 4, this bootstrapping process needs to be done manually with the help of “platformBrowserDynamic” function which is defined within the “@angular/platform-browser-dynamic” library. Before bootstrapping Angular module, it is important to define the export keyword in the module class definition statement so that we can import that class into another file. Normally, as per standard guidelines of Angular, we define this bootstrap process within the main.ts file.

  1. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';  
  2. import { SampleModule } from './app.article.module';  
  3.   
  4. platformBrowserDynamic().bootstrapModule(SampleModule);  
Bootstrap the Component

In the previous section, we discussed if there are many modules that we need to bootstrap, one module as a starting module needs to be defined within the main.ts file. But at the same time, one module always contains multiple components. Then, what happens in this scenario - which component will be starting component or how Angular will identify its root component? For this reason, we also need to bootstrap the root component so that Angular can identify it. It can be done by using the bootstrap option in “NgModule” decorator.

  1. import { NgModule } from '@angular/core';  
  2. import { HomeComponent } from './SampleCode/app.component.home';  
  3.   
  4. @NgModule({  
  5.     declarations: [HomeComponent],  
  6.     bootstrap: [HomeComponent],  
  7. })  
  8.   
  9. export class SampleModule { }  
Now, we will create a basic component which will display some data into the web pages. For that, we first create a typescript file named app.component.helloworld.ts and add the below code,
  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     selector: 'Hello-world',  
  5.     template: '<strong><b>Angular 4!</b>Hello World</strong>'  
  6. })  
  7.   
  8. export class HelloWorldComponent {  
  9.     constructor() {  
  10.     }  
  11.   
  12.     ngOnInit() {  
  13.         alert("Page Init Method Fired!!")  
  14.     }  
  15. }  
Now, add another TypeScript file named app.component.home.ts and the below code (basically this is the root component for us. We actually bootstrapped this component from the app.module.ts file
  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: 'home-page',  
  6.     templateUrl: 'app.component.home.html'  
  7. })  
  8.   
  9. export class HomeComponent {  
  10.     constructor() {  
  11.     }  
  12. }  
As per the above code, we use templateUrl properties of the component decorator for the root component. For this, we need to add an HTML file called app.component.home.html (We placed TypeScript and HTML file in the same folder location. But we can also place these two types of files in different locations. In that scenerio, we need to providethe HTML file name with related file path and the below code.
  1. <strong>Angular 4 Code Samples</strong>  
  2. <br />  
  3. <Hello-world></Hello-world>  
  4. <br />  
 Now, add another TypeScript file for Angular module and write down the code given below.
  1. import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';  
  2. import { APP_BASE_HREF } from '@angular/common';  
  3. import { BrowserModule } from '@angular/platform-browser';  
  4. import { FormsModule } from "@angular/forms";  
  5. import { HttpModule } from '@angular/http';  
  6. import { RouterModule } from '@angular/router';  
  7.   
  8. import { HomeComponent } from './SampleCode/app.component.home';  
  9. import { HelloWorldComponent } from './SampleCode/app.component.helloworld';  
  10.   
  11.   
  12. @NgModule({  
  13.     imports: [BrowserModule, FormsModule, HttpModule],  
  14.     declarations: [HomeComponent, HelloWorldComponent],  
  15.     bootstrap: [HomeComponent],  
  16.     schemas: [NO_ERRORS_SCHEMA]  
  17. })  
  18.   
  19. export class ArticleModule { }  
Now, add another file called main.ts and add the below code.
  1. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';  
  2. import { ArticleModule } from './app.article.module';  
  3.   
  4. platformBrowserDynamic().bootstrapModule(ArticleModule);  
Now, add the below code in index.html file.
  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <!--<base href="/">-->  
  5.     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  6.     <meta charset="utf-8">  
  7.     <title>Angular 4 - Console</title>  
  8.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  9.     <meta name="description" content="">  
  10.     <meta name="keywords" content="">  
  11.     <meta name="author" content="">  
  12.   
  13.     <link href="resource/css/bootstrap.min.css" rel="stylesheet">  
  14.     <link rel="stylesheet" href="resource/css/font-awesome.min.css">  
  15.     <link rel="stylesheet" href="resource/css/jquery-ui.css">  
  16.     <link href="resource/css/style.css" rel="stylesheet">  
  17.     <link rel="shortcut icon" href="img/favicon/favicon.ico">  
  18. </head>  
  19. <body>      
  20.     <div class="content">  
  21.         <home-page></home-page>  
  22.     </div>  
  23.     <footer>  
  24.         <div class="container">  
  25.             <div class="row">  
  26.                 <div class="col-md-12">  
  27.                     <p class="copy">Copyright © 2017-2018 | <a href="http://www.c-sharpcorner.com/members/debasis-saha">Debasis Saha</a> </p>  
  28.                 </div>  
  29.             </div>  
  30.         </div>  
  31.     </footer>  
  32.     <script src="resource/js/jquery.js"></script>  
  33.     <script src="resource/js/bootstrap.min.js"></script>  
  34.     <script src="resource/js/jquery-ui.min.js"></script>  
  35.     <script src="resource/js/jquery.slimscroll.min.js"></script>  
  36.     <script src="resource/js/custom.js"></script>  
  37.   
  38.     <script src="node_modules/core-js/client/shim.min.js"></script>  
  39.     <script src="node_modules/zone.js/dist/zone.js"></script>  
  40.     <script src="node_modules/systemjs/dist/system.src.js"></script>  
  41.     <script src="systemjs.config.js"></script>  
  42.     <script>  
  43.         System.import('main.js').catch(function (err) { console.error(err); });  
  44.     </script>  
  45.   
  46.     <!-- Set the base href, demo only! In your app: <base href="/"> -->  
  47.     <script>document.write('<base href="' + document.location + '" />');</script>  
  48. </body>  
  49. </html>  
Now, run the code. The output is shown below.
 
 
 
Now, we want to create another component which will use templateUrl properties in-spite of template properties. For that, create another TypeScript file named app.component.template.ts and add the below code.
  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: 'template-url',  
  6.     templateUrl: 'app.component.template.html'  
  7. })  
  8.   
  9. export class TemplateUrlComponent {      
  10.     constructor() {  
  11.   
  12.     }  
  13. }  
 Add another HTML file named app.component.template.html and add the below code.
  1. <div>  
  2.     <strong>Angular 4 Component with Template & Style Decorator</strong>  
  3.     <br />  
  4.     <strong>C# Corner</strong>  
  5. </div>  
Now, import the component in the app.module.ts file and add the component name within the declaration properties. 
 
Add the HTML attribute in the app.component.home.html file as below.
  1. <strong>Angular 4 Code Samples</strong>  
  2. <br />  
  3. <Hello-world></Hello-world>  
  4. <br />  
  5. <template-url></template-url>  
  6. <br />  
Now, run the code. The output s shown below.

 

Now, in this case, we can apply the custom style using CSS for the HTML tags. For CSS style, we need to use styles properties, as below.
  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: 'template-style',  
  6.     templateUrl: 'app.component.template.html',  
  7.     styles: ['strong{color:red;font-weight:bold}','strong{color:blue}']  
  8. })  
  9.   
  10. export class TemplateUrlComponent {      
  11.     constructor() {  
  12.   
  13.     }  
  14. }  
Now, run the code or refresh the browser.

 
<< Read Part 1 of this article here                           Read Part 3 of this article series here >>                                   


Similar Articles