Angular 8 – Working Example ”; Previous Next Here, we will study about the complete step by step working example with regards to Angular 8. Let us create an Angular application to check our day to day expenses. Let us give ExpenseManager as our choice for our new application. Create an application Use below command to create the new application. cd /path/to/workspace ng new expense-manager Here, new is one of the command of the ng CLI application. It will be used to create new application. It will ask some basic question in order to create new application. It is enough to let the application choose the default choices. Regarding routing question as mentioned below, specify No. Would you like to add Angular routing? No Once the basic questions are answered, the ng CLI application create a new Angular application under expense-manager folder. Let us move into the our newly created application folder. cd expense-manager Let us start the application using below comman. ng serve Let us fire up a browser and opens http://localhost:4200. The browser will show the application as shown below − Let us change the title of the application to better reflect our application. Open src/app/app.component.ts and change the code as specified below − export class AppComponent { title = ”Expense Manager”; } Our final application will be rendered in the browser as shown below − Add a component Create a new component using ng generate component command as specified below − ng generate component expense-entry Output The output is as follows − CREATE src/app/expense-entry/expense-entry.component.html (28 bytes) CREATE src/app/expense-entry/expense-entry.component.spec.ts (671 bytes) CREATE src/app/expense-entry/expense-entry.component.ts (296 bytes) CREATE src/app/expense-entry/expense-entry.component.css (0 bytes) UPDATE src/app/app.module.ts (431 bytes) Here, ExpenseEntryComponent is created under src/app/expense-entry folder. Component class, Template and stylesheet are created. AppModule is updated with new component. Add title property to ExpenseEntryComponent (src/app/expense-entry/expense-entry.component.ts) component. import { Component, OnInit } from ”@angular/core”; @Component({ selector: ”app-expense-entry”, templateUrl: ”./expense-entry.component.html”, styleUrls: [”./expense-entry.component.css”] }) export class ExpenseEntryComponent implements OnInit { title: string; constructor() { } ngOnInit() { this.title = “Expense Entry” } } Update template, src/app/expense-entry/expense-entry.component.html with below content. <p>{{ title }}</p> Open src/app/app.component.html and include newly created component. <h1>{{ title }}</h1> <app-expense-entry></app-expense-entry> Here, app-expense-entry is the selector value and it can be used as regular HTML Tag. The output of the application is as shown below − Include bootstrap Let us include bootstrap into our ExpenseManager application using styles option and change the default template to use bootstrap components. Open command prompt and go to ExpenseManager application. cd /go/to/expense-manager Install bootstrap and JQuery library using below commands npm install –save [email protected] [email protected] Here, We have installed JQuery, because, bootstrap uses jquery extensively for advanced components. Option angular.json and set bootstrap and jquery library path. { “projects”: { “expense-manager”: { “architect”: { “build”: { “builder”:”@angular-devkit/build-angular:browser”, “options”: { “outputPath”: “dist/expense-manager”, “index”: “src/index.html”, “main”: “src/main.ts”, “polyfills”: “src/polyfills.ts”, “tsConfig”: “tsconfig.app.json”, “aot”: false, “assets”: [ “src/favicon.ico”, “src/assets” ], “styles”: [ “./node_modules/bootstrap/dist/css/bootstrap.css”, “src/styles.css” ], “scripts”: [ “./node_modules/jquery/dist/jquery.js”, “./node_modules/bootstrap/dist/js/bootstrap.js” ] }, }, } }}, “defaultProject”: “expense-manager” } Here, scripts option is used to include JavaScript library. JavaScript registered through scripts will be available to all Angular components in the application. Open app.component.html and change the content as specified below <!– Navigation –> <nav class=”navbar navbar-expand-lg navbar-dark bg-dark static-top”> <div class=”container”> <a class=”navbar-brand” href=”#”>{{ title }}</a> <button class=”navbar-toggler” type=”button” data-toggle=”collapse” data-target=”#navbarResponsive” aria-controls=”navbarResponsive” aria-expanded=”false” aria-label=”Toggle navigation”> <span class=”navbar-toggler-icon”> </span> </button> <div class=”collapse navbar-collapse” id=”navbarResponsive”> <ul class=”navbar-nav ml-auto”> <li class=”nav-item active”> <a class=”nav-link” href=”#”>Home <span class=”sr-only”>(current) </span> </a> </li> <li class=”nav-item”> <a class=”nav-link” href=”#”>Report</a> </li> <li class=”nav-item”> <a class=”nav-link” href=”#”>Add Expense</a> </li> <li class=”nav-item”> <a class=”nav-link” href=”#”>About</a> </li> </ul> </div> </div> </nav> <app-expense-entry></app-expense-entry> Here, Used bootstrap navigation and containers. Open src/app/expense-entry/expense-entry.component.html and place below content. <!– Page Content –> <div class=”container”> <div class=”row”> <div class=”col-lg-12 text-center” style=”padding-top: 20px;”> <div class=”container” style=”padding-left: 0px; padding-right: 0px;”> <div class=”row”> <div class=”col-sm” style=”text-align: left;”> {{ title }} </div> <div class=”col-sm” style=”text-align: right;”> <button type=”button” class=”btn btn-primary”>Edit</button> </div> </div> </div> <div class=”container box” style=”margin-top: 10px;”> <div class=”row”> <div class=”col-2″ style=”text-align: right;”> <strong><em>Item:</em></strong> </div> <div class=”col” style=”text-align: left;”> Pizza </div> </div> <div class=”row”> <div class=”col-2″ style=”text-align: right;”> <strong><em>Amount:</em></strong> </div> <div class=”col” style=”text-align: left;”> 20 </div> </div> <div class=”row”> <div class=”col-2″ style=”text-align: right;”> <strong><em>Category:</em></strong> </div> <div class=”col” style=”text-align: left;”> Food </div> </div> <div class=”row”> <div class=”col-2″ style=”text-align: right;”> <strong><em>Location:</em></strong> </div> <div class=”col” style=”text-align: left;”> Zomato </div> </div> <div class=”row”> <div class=”col-2″ style=”text-align: right;”> <strong><em>Spend On:</em></strong> </div> <div class=”col” style=”text-align: left;”> June 20, 2020 </div> </div> </div> </div> </div> </div> Restart the application. The output of the application is as follows − We will improve the application to handle dynamic expense entry in next chapter. Add an interface Create ExpenseEntry interface (src/app/expense-entry.ts) and add id, amount, category, Location, spendOn and createdOn. export interface ExpenseEntry { id: number; item: string; amount: number; category: string; location: string; spendOn: Date; createdOn: Date; } Import ExpenseEntry into ExpenseEntryComponent. import { ExpenseEntry
Category: angular8
Angular 8 – Quick Guide
Angular 8 – Quick Guide ”; Previous Next Angular 8 – Introduction Angular 8 is a TypeScript based full-stack web framework for building web and mobile applications. One of the major advantage is that the Angular 8 support for web application that can fit in any screen resolution. Angular application is fully compatible for mobiles, tablets, laptops or desktops. Angular 8 has an excellent user interface library for web developers which contains reusable UI components. This functionality helps us to create Single Page Applications (SPA). SPA is reactive and fast application. For example, if you have a button in single page and click on the button then the action performs dynamically in the current page without loading the new page from the server. Angular 8 is Typescript based object oriented programming and support features for server side programming as well. Comparison of angular versions As we know already, Google releases the version of Angular for the improvement of mobile and web development capabilities. All the released versions are backward compatible and can be updated easily to the newer version. Let’s go through the comparison of released versions. AngularJS AngularJs is very powerful JavaScript framework. It was released in October 2010. AngularJS based on Model View Controller (MVC) architecture and automatically handles JavaScript code suitable for each browser. Angular 2.0 Angular 2.0 was released in September 2016. It is re-engineered and rewritten version of AngularJS. AngularJs had a focus on controllers but, version 2 has changed focus on components. Components are the main building block of application. It supports features for speed in rendering, updating pages and building cross-platform native mobile apps for Google Android and iOS. Angular 4.0 Angular 4.0 was released in March 2017. It is updated to TypeScript 2.2, supports ng if-else conditions whereas Angular 2 supported only if conditions. Angular 4.0 introduces animation packages, Http search parameters and finally angular 4 applications are smaller and faster. Angular 5.0 Angular 5.0 was released in November 2017. It supported some of the salient features such as HTTPClient API, Lambda support, Improved Compiler and build optimizer. Angular 6.0 Angular 6.0 was released in May 2018. Features added to this version are updated Angular CLI, updated CDK, updated Angular Material, multiple validators and usage of reactive JS library. Angular 7.0 Angular 7.0 was released in October 2018. Some of salient features are Google supported community, POJO based development, modular structure, declarative user interface and modular structure. Angular 8 New features Angular 8 comes up with the following new attractive features − Bazel support − If your application uses several modules and libraries, Bazel concurrent builds helps to load faster in your application. Lazy loading − Angular 8 splits AppRoutingModule into smaller bundles and loads the data in the DOM. Differential loading − When you create an application, Angular CLI generates modules and this will be loaded automatically then browser will render the data. Web worker − It is running in the background, without affecting the performance of a page. Improvement of CLI workflow − Angular 8 CLI commands ng-build, ng-test and ng-run are extended to third party libraries. Router Backward Compatibility − Angular router backward compatibility feature helps to create path for larger projects so user can easily add their coding with the help of lazy coding. Opt-in usage sharing − User can opt into share Angular CLI usage data. Applications Some of the popular website using Angular Framework are listed below − Weather.com − It is one of the leading forecasting weather report website. Youtube − It is a video and sharing website hosted by Google. Netflix − It is a technology and media services provider. PayPal − It is an online payment system. Angular 8 – Installation This chapter explains about how to install Angular 8 on your machine. Before moving to the installation, let’s verify the prerequisite first. Prerequisite As we know already, Angular is written in TypeScript. We need Node and npm to compile the files into JavaScript after that, we can deploy our application. For this purpose, Node.js must be installed in your system. Hopefully, you have installed Node.js on your machine. We can check it using the below command − node –version You could see the version of node. It is show below − v14.2.0 If Node is not installed, you can download and install by visiting the following link − https://nodejs.org/en/download/. Angular 8 installation Angular 8 CLI installation is based on very simple steps. It will take not more than five minutes to install. npm is used to install Angular 8 CLI. Once Node.js is installed, npm is also installed. If you want verify it, type the below command npm -v You could see the version below − 6.14.4 Let’s install Angular 8 CLI using npmas follows − npm install -g @angular/cli@^8.0.0 To verify Angular 8 is properly installed on your machine, type the below command − ng version You could see the following response − Angular CLI: 8.3.26 Node: 14.2.0 OS: win32 x64 Angular: … Package Version —————————————————— @angular-devkit/architect 0.803.26 @angular-devkit/core 8.3.26 @angular-devkit/schematics 8.3.26 @schematics/angular 8.3.26 @schematics/update 0.803.26 rxjs 6.4.0 Angular 8 – Creating First Application Let us create a simple angular application and analyse the structure of the basic angular application. Let us check whether the Angular Framework is installed in our system and the version of the installed Angular version using below command − ng –version Here, ng is the CLI application used to create, manage and run Angular Application. It written in JavaScript
Angular 8 – Server Side Rendering ”; Previous Next Server side Rendering (SSR) is a modern technique to convert a Single Page Application (SPA) running in the browser into a server based application. Usually, in SPA, the server returns a simple index.html file with the reference to the JavaScript based SPA app. The SPA app take over from there, configure the entire application, process the request and then send the final response. But in SSR supported application, the server as well do all the necessary configuration and then send the final response to the browser. The browser renders the response and start the SPA app. SPA app takeover from there and further request are diverted to SPA app. The flow of SPA and SSR is as shown in below diagram. Converting a SPA application to SSR provides certain advantages and they are as follows − Speed − First request is relatively fast. One of the main drawback of SPA is slow initial rendering. Once the application is rendered, SPA app is quite fast. SSR fixes the initial rendering issue. SEO Friendly − Enables the site to be SEO friendly. Another main disadvantage of SPA is not able to crawled by web crawler for the purpose of SEO. SSR fixes the issue. Angular Universal To enable SSR in Angular, Angular should be able to rendered in the server. To make it happen, Angular provides a special technology called Angular Universal. It is quite new technology and it is continuously evolving. Angular Universal knows how to render Angular application in the server. We can upgrade our application to Angular Universal to support SSR. Print Page Previous Next Advertisements ”;
Angular 8 – Directives
Angular 8 – Directives ”; Previous Next Angular 8 directives are DOM elements to interact with your application. Generally, directive is a TypeScript function. When this function executes Angular compiler checked it inside DOM element. Angular directives begin with ng- where ng stands for Angular and extends HTML tags with @directive decorator. Directives enables logic to be included in the Angular templates. Angular directives can be classified into three categories and they are as follows − Attribute directives Used to add new attributes for the existing HTML elements to change its look and behaviour. <HTMLTag [attrDirective]=”value” /> For example, <p [showToolTip]=”Tips” /> Here, showToolTip refers an example directive, which when used in a HTML element will show tips while user hovers the HTML element. Structural directives Used to add or remove DOM elements in the current HTML document. <HTMLTag [structuralDirective]=”value” /> For example, <div *ngIf=”isNeeded”> Only render if the *isNeeded* value has true value. </div> Here, ngIf is a built-in directive used to add or remove the HTML element in the current HTML document. Angular provides many built-in directive and we will learn in later chapters. Component based directives Component can be used as directives. Every component has Input and Output option to pass between component and its parent HTML elements. <component-selector-name [input-reference]=”input-value”> … </component-selector-name> For example, <list-item [items]=”fruits”> … </list-item> Here, list-item is a component and items is the input option. We will learn how to create component and advanced usages in the later chapters. Before moving to this topic, let’s create a sample application (directive-app) in Angular 8 to work out the learnings. Open command prompt and create new Angular application using below command − cd /go/to/workspace ng new directive-app cd directive-app Create a test component using Angular CLI as mentioned below − ng generate component test The above create a new component and the output is as follows − CREATE src/app/test/test.component.scss (0 bytes) CREATE src/app/test/test.component.html (19 bytes) CREATE src/app/test/test.component.spec.ts (614 bytes) CREATE src/app/test/test.component.ts (262 bytes) UPDATE src/app/app.module.ts (545 bytes) Run the application using below command − ng serve DOM Overview Let us have a look at DOM model in brief. DOM is used to define a standard for accessing documents. Generally, HTML DOM model is constructed as a tree of objects. It is a standard object model to access html elements. We can use DOM model in Angular 8 for the below reasons − We can easily navigate document structures with DOM elements. We can easily add html elements. We can easily update elements and its contents. Structural directives Structural directives change the structure of DOM by adding or removing elements. It is denoted by * sign with three pre-defined directives NgIf, NgFor and NgSwitch. Let’s understand one by one in brief. NgIf directive NgIf directive is used to display or hide data in your application based on the condition becomes true or false. We can add this to any tag in your template. Let us try ngIf directive in our directive-app application. Add the below tag in test.component.html. <p>test works!</p> <div *ngIf=”true”>Display data</div> Add the test component in your app.component.html file as follows − <app-test></app-test> Start your server (if not started already) using the below command − ng serve Now, run your application and you could see the below response − If you set the condition ngIf=“false” then, contents will be hidden. ngIfElse directive ngIfElse is similar to ngIf except, it provides option to render content during failure scenario as well. Let’s understand how ngIfElse works by doing a sample. Add the following code in test.component.ts file. export class TestComponent implements OnInit { isLogIn : boolean = false; isLogOut : boolean = true; } Add the following code in test.component.html file as follows − <p>ngIfElse example!</p> <div *ngIf=”isLogIn; else isLogOut”> Hello you are logged in </div> <ng-template #isLogOut> You”re logged out.. </ng-template> Finally, start your application (if not done already) using the below command − ng serve Now, run your application and you could see the below response − Here, isLogOut value is assigned as true, so it goes to else block and renders ng-template. We will learn ng-template later in this chapter. ngFor directive ngFor is used to repeat a portion of elements from the list of items. Let’s understand how ngFor works by doing a sample. Add the list in test.component.ts file as shown below − list = [1,2,3,4,5]; Add ngFor directive in test.component.html as shown below − <h2>ngFor directive</h2> <ul> <li *ngFor=”let l of list”> {{l}} </li> </ul> Here, the let keyword creates a local variable and it can be referenced anywhere in your template. The let l creates a template local variable to get the list elements. Finally, start your application (if not done already) using the below command − ng serve Now, run your application and you could see the below response − trackBy Sometimes, ngFor performance is low with large lists. For example, when adding new item or remove any item in the list may trigger several DOM manipulations. To iterate over large objects collection, we use trackBy. It is used to track when elements are added or removed. It is performed by trackBy method. It has two arguments index and element. Index is used to identity each element uniquely. Simple example is defined below. Let’s understand how trackBy works along
Angular 8 – Reactive Programming ”; Previous Next Reactive programming is a programming paradigm dealing with data streams and the propagation of changes. Data streams may be static or dynamic. An example of static data stream is an array or collection of data. It will have an initial quantity and it will not change. An example for dynamic data stream is event emitters. Event emitters emit the data whenever the event happens. Initially, there may be no events but as the time moves on, events happens and it will gets emitted. Reactive programming enables the data stream to be emitted from one source called Observable and the emitted data stream to be caught by other sources called Observer through a process called subscription. This Observable / Observer pattern or simple Observer pattern greatly simplifies complex change detection and necessary updating in the context of the programming. JavaScript does not have the built-in support for Reactive Programming. RxJs is a JavaScript Library which enables reactive programming in JavaScript. Angular uses RxJs library extensively to do below mentioned advanced concepts − Data transfer between components. HTTP client. Router. Reactive forms. Let us learn reactive programming using RxJs library in this chapter. Observable As learn earlier, Observable are data sources and they may be static or dynamic. Rxjs provides lot of method to create Observable from common JavaScript Objects. Let us see some of the common methods. of − Emit any number of values in a sequence and finally emit a complete notification. const numbers$ = of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Here, numbers$ is an Observable object, which when subscribed will emit 1 to 10 in a sequence. Dollar sign ($) at the end of the variable is to identify that the variable is Observable. range − Emit a range of number in sequence. const numbers$ = range(1,10) from − Emit array, promise or iterable. const numbers$ = from([1,2,3,4,5,6,7,8,9,10]); ajax − Fetch a url through AJAX and then emit the response. const api$ = ajax({ url: ”https://httpbin.org/delay/1”, method: ”POST”, headers: { ”Content-Type”: ”application/text” }, body: “Hello” }); Here, https://httpbin.org is a free REST API service which will return the supplied body content in the JSON format as specified below − { “args”: {}, “data”: “Hello”, “files”: {}, “form”: {}, “headers”: { “Accept”: “text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9”, “Accept-Encoding”: “gzip, deflate, br”, “Accept-Language”: “en-US,en;q=0.9”, “Host”: “httpbin.org”, “Sec-Fetch-Dest”: “document”, “Sec-Fetch-Mode”: “navigate”, “Sec-Fetch-Site”: “none”, “Upgrade-Insecure-Requests”: “1”, “User-Agent”: “Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36”, “X-Amzn-Trace-Id”: “Root=1-5eeef468-015d8f0c228367109234953c” }, “origin”: “ip address”, “url”: “https://httpbin.org/delay/1″ } fromEvent − Listen to an HTML element’s event and then emit the event and its property whenever the listened event fires. const clickEvent$ = fromEvent(document.getElementById(”counter”), ”click”); Angular internally uses the concept extensively to provide data transfer between components and for reactive forms. Subscribing process Subscribing to an Observable is quite easy. Every Observable object will have a method, subscribe for the subscription process. Observer need to implement three callback function to subscribe to the Observable object. They are as follows − next − Receive and process the value emitted from the Observable error − Error handling callback complete − Callback function called when all data from Observable are emitted. Once the three callback functions are defined, Observable’s subscribe method has to be called as specified below − const numbers$ = from([1,2,3,4,5,6,7,8,9,10]); // observer const observer = { next: (num: number) => { this.numbers.push(num); this.val1 += num }, error: (err: any) => console.log(err), complete: () => console.log(“Observation completed”) }; numbers$.subscribe(observer); Here, next − method get the emitted number and then push it into the local variable, this.numbers. next − method also adding the number to local variable, this.val1. error − method just writes the error message to console. complete − method also writes the completion message to console. We can skip error and complete method and write only the next method as shown below − number$.subscribe((num: number) => { this.numbers.push(num); this.val1 += num; }); Operations Rxjs library provides some of the operators to process the data stream. Some of the important operators are as follows − filter − Enable to filter the data stream using callback function. const filterFn = filter( (num : number) => num > 5 ); const filteredNumbers$ = filterFn(numbers$); filteredNumbers$.subscribe( (num : number) => { this.filteredNumbers.push(num); this.val2 += num } ); map − Enables to map the data stream using callback function and to change the data stream itself. const mapFn = map( (num : number) => num + num ); const mappedNumbers$ = mappedFn(numbers$); pipe − Enable two or more operators to be combined. const filterFn = filter( (num : number) => num > 5 ); const mapFn = map( (num : number) => num + num ); const processedNumbers$ = numbers$.pipe(filterFn, mapFn); processedNumbers$.subscribe( (num : number) => { this.processedNumbers.push(num); this.val3 += num } ); Let us create a sample application to try out the reaction programming concept learned in this chapter. Create a new application, reactive using below command − ng new reactive Change the directory to our newly created application. cd reactive Run the application. ng serve Change the AppComponent component code (src/app/app.component.ts) as specified below − import { Component, OnInit } from ”@angular/core”; import { Observable, of, range, from, fromEvent } from ”rxjs”; import { ajax } from ”rxjs/ajax”; import {
Angular 8 – Services and Dependency Injection ”; Previous Next As learned earlier, Services provides specific functionality in an Angular application. In a given Angular application, there may be one or more services can be used. Similarly, an Angular component may depend on one or more services. Also, Angular services may depend on another services to work properly. Dependency resolution is one of the complex and time consuming activity in developing any application. To reduce the complexity, Angular provides Dependency Injection pattern as one of the core concept. Let us learn, how to use Dependency Injection in Angular application in this chapter. Create Angular service An Angular service is plain Typescript class having one or more methods (functionality) along with @Injectable decorator. It enables the normal Typescript class to be used as service in Angular application. import { Injectable } from ”@angular/core”; @Injectable() export class DebugService { constructor() { } } Here, @Injectable decorator converts a plain Typescript class into Angular service. Register Angular service To use Dependency Injection, every service needs to be registered into the system. Angular provides multiple option to register a service. They are as follows − ModuleInjector @ root level ModuleInjector @ platform level ElementInjector using providers meta data ElementInjector using viewProviders meta data NullInjector ModuleInjector @ root ModuleInjector enforces the service to used only inside a specific module. ProvidedInmeta data available in @Injectable has to be used to specify the module in which the service can be used. The value should refer to the one of the registered Angular Module (decorated with @NgModule). root is a special option which refers the root module of the application. The sample code is as follows − import { Injectable } from ”@angular/core”; @Injectable({ providedIn: ”root”, }) export class DebugService { constructor() { } } ModuleInjector @ platform Platform Injector is one level higher than ModuleInject and it is only in advanced and rare situation. Every Angular application starts by executing PreformBrowserDynamic().bootstrap method (see main.js), which is responsible for bootstrapping root module of Angular application. PreformBrowserDynamic() method creates an injector configured by PlatformModule. We can configure platform level services using platformBrowser() method provided by PlatformModule. NullInjector NullInjector is one level higher than platform level ModuleInjector and is in the top level of the hierarchy. We could not able to register any service in the NullInjector. It resolves when the required service is not found anywhere in the hierarchy and simply throws an error. ElementInjector using providers ElementInjector enforces the service to be used only inside some particular components. providers and ViewProviders meta data available in @Component decorator is used to specify the list of services to be visible for the particular component. The sample code to use providers is as follows − ExpenseEntryListComponent // import statement import { DebugService } from ”../debug.service”; // component decorator @Component({ selector: ”app-expense-entry-list”, templateUrl: ”./expense-entry-list.component.html”, styleUrls: [”./expense-entry-list.component.css”], providers: [DebugService] }) Here, DebugService will be available only inside the ExpenseEntryListComponent and its view. To make DebugService in other component, simply use providers decorator in necessary component. ElementInjector using viewProviders viewProviders is similar to provider except it does not allow the service to be used inside the component’s content created using ng-content directive. ExpenseEntryListComponent // import statement import { DebugService } from ”../debug.service”; // component decorator @Component({ selector: ”app-expense-entry-list”, templateUrl: ”./expense-entry-list.component.html”, styleUrls: [”./expense-entry-list.component.css”], viewProviders: [DebugService] }) Parent component can use a child component either through its view or content. Example of a parent component with child and content view is mentioned below − Parent component view / template <div> child template in view <child></child> </div> <ng-content></ng-content> child component view / template <div> child template in view </div> Parent component usage in a template (another component) <parent> <!– child template in content –> <child></child> </parent> Here, child component is used in two place. One inside the parent’s view. Another inside parent content. Services will be available in child component, which is placed inside parent’s view. Services will not be available in child component, which is placed inside parent’s content. Resolve Angular service Let us see how a component can resolve a service using the below flow diagram. Here, First, component tries to find the service registered using viewProviders meta data. If not found, component tries to find the service registered using providers meta data. If not found, Component tries to find the service registered using ModuleInjector If not found, component tries to find the service registered using PlatformInjector If not found, component tries to find the service registered using NullInjector, which always throws error. The hierarchy of the Injector along with work flow of the resolving the service is as follows − Resolution Modifier As we learn in the previous chapter, the resolution of the service starts from component and stops either when a service is found or NUllInjector is reached. This is the default resolution and it can be changed using Resolution Modifier. They are as follows − Self() Self() start and stops the search for the service in its current ElementInjector itself. import { Self } from ”@angular/core”; constructor(@Self() public debugService: DebugService) {} SkipSelf() SkipSelf() is just opposite to Self(). It skips the current ElementInjector and starts the search for service from its parent ElementInjector. import { SkipSelf } from ”@angular/core”; constructor(@SkipSelf() public debugService: DebugService) {} Host() Host() stop the search for the service in its host
Routing and Navigation
Angular 8 – Routing and Navigation ”; Previous Next Navigation is one of the important aspect in a web application. Even though a single page application (SPA) does not have multiple page concept, it does moves from one view (list of expenses) to another view (expense details). Providing clear and understandable navigation elements decides the success of an application. Angular provides extensive set of navigation feature to accommodate simple scenario to complex scenario. The process of defining navigation element and the corresponding view is called Routing. Angular provides a separate module, RouterModule to set up the navigation in the Angular application. Let us learn the how to do the routing in Angular application in this chapter. Configure Routing Angular CLI provides complete support to setup routing during the application creation process as well as during working an application. Let us create a new application with router enabled using below command − ng new routing-app –routing Angular CLI generate a new module, AppRoutingModuele for routing purpose. The generated code is as follows − import { NgModule } from ”@angular/core”; import { Routes, RouterModule } from ”@angular/router”; const routes: Routes = []; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } Here, Imports RouterModule and Routes from @angular/router package. RouterMoudle provides functionality to configure and execute routing in the application. Routes is the type used to setup the navigation rules. Routes is the local variable (of type Routes) used to configure the actual navigation rules of the application. RouterMoudle.forRoot() method will setup the navigation rules configured in the routes variable. Angular CLI include the generated AppRoutingModule in AppComponent as mentioned below − import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { AppRoutingModule } from ”./app-routing.module”; import { AppComponent } from ”./app.component”; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Here, AppComponent imports the AppRoutingModule module using imports meta data. Angular CLI provides option to set routing in the existing application as well. The general command to include routing in an existing application is as follows − ng generate module my-module –routing This will generate new module with routing features enabled. To enable routing feature in the existing module (AppModule), we need to include extra option as specified below − ng generate module app-routing –module app –flat Here, –module app configures the newly created routing module, AppRoutingModule in the AppModule module. Let us configure the routing module in ExpenseManager application. Open command prompt and go to project root folder. cd /go/to/expense-manager Generate routing module using below command − ng generate module app-routing –module app –flat Output The output is mentioned below − CREATE src/app/app-routing.module.ts (196 bytes) UPDATE src/app/app.module.ts (785 bytes) Here, CLI generate AppRoutingModule and then, configures it in AppModule Creating routes Creating a route is simple and easy. The basic information to create a route is given below − Target component to be called. The path to access the target component. The code to create a simple route is mentioned below − const routes: Routes = [ { path: ”about”, component: AboutComponent }, ]; Here, Routes is the variable in the AppRoutingModule. about is the path and AboutComponent is the target / destination component. When user requests http://localhost:4200/about url, the path matches with about rule and then AboutComponent will be called. Accessing routes Let us learn how to use the configured routes in the application. Accessing the route is a two step process. Include router-outlet tag in the root component template. <router-outlet></router-outlet> Use routerLink and routerLinkActive property in the required place. <a routerLink=”/about” routerLinkActive=”active”>First Component</a> Here, routerLink set the route to be called using the path. routerLinkActive set the CSS class to be used when the route is activated. Sometime, we need to access routing inside the component instead of template. Then, we need to follow below steps − Inject instance of Router and ActivatedRoute in the corresponding component. import { Router, ActivatedRoute } from ”@angular/router”; constructor(private router: Router, private route: ActivatedRoute) Here, Router provides the function to do routing operations. Route refers the current activate route. Use router’s navigate function. this.router.navigate([”about”]); Here, navigate function expects an array with necessary path information. Using relative path Route path is similar to web page URL and it supports relative path as well. To access AboutComponent from another component, say HomePageComponent, simple use .. notation as in web url or folder path. <a routerLink=”../about”>Relative Route to about component</a> To access relative path in the component − import { NavigationExtras } from ”@angular/router”; this.router.navigate([”about”], { relativeTo: this.route }); Here, relativeTo is available under NavigationExtras class. Route ordering Route ordering is very important in a route configuration. If same path is configured multiple times, then the first matched path will get called. If the first match fails due to some reason, then the second match will get called. Redirect routes Angular route allows a path to get redirected to another path. redirectTo is the option to set redirection path. The sample route is as follows − const routes: Routes = [ { path: ””, redirectTo: ”/about” }, ]; Here, redirectTo sets about as the redirection path if the actual path matches empty string. Wildcard routes Wildcard route will match any path. It is created using **
Angular 8 – Home
Angular 8 Tutorial PDF Version Quick Guide Resources Job Search Discussion Angular 8 is an open source, TypeScript based frontend web application framework. Angular 8 has been released by Google’s Angular community. This tutorial starts with the architecture of Angular 8,setup simple project, data binding, then walks through forms, templates, routing and explains about Angular 8 new features. Finally, conclude with step by step working example. Audience This tutorial is prepared for professionals who are aspiring to make a career in the field of Web application developer. This tutorial is intended to make you comfortable in getting started with the Angular8 concepts with examples. Prerequisites Before proceeding with the various types of concepts given in this tutorial, we assume that the readers have the basic knowledge on HTML, CSS and OOPS concepts. In addition to this, it will be very helpful, if the readers have a sound knowledge on TypeScript and JavaScript. Print Page Previous Next Advertisements ”;
Angular 8 – Http Client Programming ”; Previous Next Http client programming is a must needed feature in every modern web application. Nowadays, lot of application exposes their functionality through REST API (functionality over HTTP protocol). With this in mind, Angular Team provides extensive support to access HTTP server. Angular provides a separate module, HttpClientModule and a service, HttpClient to do HTTP programming. Let us learn how to how to use HttpClient service in this chapter. Developer should have a basic knowledge in Http programming to understand this chapter. Expense REST API The prerequisite to do Http programming is the basic knowledge of Http protocol and REST API technique. Http programming involves two part, server and client. Angular provides support to create client side application. Express a popular web framework provides support to create server side application. Let us create an Expense Rest API using express framework and then access it from our ExpenseManager application using Angular HttpClient service. Open a command prompt and create a new folder, express-rest-api. cd /go/to/workspace mkdir express-rest-api cd expense-rest-api Initialise a new node application using below command − npm init npm init will ask some basic questions like project name (express-rest-api), entry point (server.js), etc., as mentioned below − This utility will walk you through creating a package.json file. It only covers the most common items, and tries to guess sensible defaults. See `npm help json` for definitive documentation on these fields and exactly what they do. Use `npm install <pkg>` afterwards to install a package and save it as a dependency in the package.json file. Press ^C at any time to quit. package name: (expense-rest-api) version: (1.0.0) description: Rest api for Expense Application entry point: (index.js) server.js test command: git repository: keywords: author: license: (ISC) About to write to pathtoworkspaceexpense-rest-apipackage.json: { “name”: “expense-rest-api”, “version”: “1.0.0”, “description”: “Rest api for Expense Application”, “main”: “server.js”, “scripts”: { “test”: “echo “Error: no test specified” && exit 1″ }, “author”: “”, “license”: “ISC” } Is this OK? (yes) yes Install express, sqlite and cors modules using below command − npm install express sqlite3 cors Create a new file sqlitedb.js and place below code − var sqlite3 = require(”sqlite3”).verbose() const DBSOURCE = “expensedb.sqlite” let db = new sqlite3.Database(DBSOURCE, (err) => { if (err) { console.error(err.message) throw err }else{ console.log(”Connected to the SQLite database.”) db.run(`CREATE TABLE expense ( id INTEGER PRIMARY KEY AUTOINCREMENT, item text, amount real, category text, location text, spendOn text, createdOn text )`, (err) => { if (err) { console.log(err); }else{ var insert = ”INSERT INTO expense (item, amount, category, location, spendOn, createdOn) VALUES (?,?,?,?,?,?)” db.run(insert, [”Pizza”, 10, ”Food”, ”KFC”, ”2020-05-26 10:10”, ”2020-05-26 10:10”]) db.run(insert, [”Pizza”, 9, ”Food”, ”Mcdonald”, ”2020-05-28 11:10”, ”2020-05-28 11:10”]) db.run(insert, [”Pizza”, 12, ”Food”, ”Mcdonald”, ”2020-05-29 09:22”, ”2020-05-29 09:22”]) db.run(insert, [”Pizza”, 15, ”Food”, ”KFC”, ”2020-06-06 16:18”, ”2020-06-06 16:18”]) db.run(insert, [”Pizza”, 14, ”Food”, ”Mcdonald”, ”2020-06-01 18:14”, ”2020-05-01 18:14”]) } } ); } }); module.exports = db Here, we are creating a new sqlite database and load some sample data. Open server.js and place below code − var express = require(“express”) var cors = require(”cors”) var db = require(“./sqlitedb.js”) var app = express() app.use(cors()); var bodyParser = require(“body-parser”); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); var HTTP_PORT = 8000 app.listen(HTTP_PORT, () => { console.log(“Server running on port %PORT%”.replace(“%PORT%”,HTTP_PORT)) }); app.get(“/”, (req, res, next) => { res.json({“message”:”Ok”}) }); app.get(“/api/expense”, (req, res, next) => { var sql = “select * from expense” var params = [] db.all(sql, params, (err, rows) => { if (err) { res.status(400).json({“error”:err.message}); return; } res.json(rows) }); }); app.get(“/api/expense/:id”, (req, res, next) => { var sql = “select * from expense where id = ?” var params = [req.params.id] db.get(sql, params, (err, row) => { if (err) { res.status(400).json({“error”:err.message}); return; } res.json(row) }); }); app.post(“/api/expense/”, (req, res, next) => { var errors=[] if (!req.body.item){ errors.push(“No item specified”); } var data = { item : req.body.item, amount: req.body.amount, category: req.body.category, location : req.body.location, spendOn: req.body.spendOn, createdOn: req.body.createdOn, } var sql = ”INSERT INTO expense (item, amount, category, location, spendOn, createdOn) VALUES (?,?,?,?,?,?)” var params =[data.item, data.amount, data.category, data.location, data.spendOn, data.createdOn] db.run(sql, params, function (err, result) { if (err){ res.status(400).json({“error”: err.message}) return; } data.id = this.lastID; res.json(data); }); }) app.put(“/api/expense/:id”, (req, res, next) => { var data = { item : req.body.item, amount: req.body.amount, category: req.body.category, location : req.body.location, spendOn: req.body.spendOn } db.run( `UPDATE expense SET item = ?, amount = ?, category = ?, location = ?, spendOn = ? WHERE id = ?`, [data.item, data.amount, data.category, data.location,data.spendOn, req.params.id], function (err, result) { if (err){ console.log(err); res.status(400).json({“error”: res.message}) return; } res.json(data) }); }) app.delete(“/api/expense/:id”, (req, res, next) => { db.run( ”DELETE FROM expense WHERE id = ?”, req.params.id, function (err, result) { if (err){ res.status(400).json({“error”: res.message}) return; } res.json({“message”:”deleted”, changes: this.changes}) }); }) app.use(function(req, res){ res.status(404); }); Here, we create a basic CURD rest api to select, insert, update and delete expense entry. Run the application using below command − npm run start Open a browser, enter http://localhost:8000/ and press enter. You will see below response − { “message”: “Ok” } It confirms our application is working fine. Change the url to http://localhost:8000/api/expense and you will see all the expense entries in JSON format. [ { “id”: 1, “item”: “Pizza”, “amount”: 10, “category”: “Food”, “location”: “KFC”, “spendOn”: “2020-05-26 10:10”, “createdOn”: “2020-05-26 10:10″ }, { “id”: 2, “item”: “Pizza”, “amount”: 14, “category”: “Food”, “location”: “Mcdonald”, “spendOn”: “2020-06-01 18:14”, “createdOn”: “2020-05-01 18:14″ }, { “id”: 3, “item”: “Pizza”, “amount”: 15, “category”:
Angular 8 – Internationalization (i18n) ”; Previous Next Internationalization (i18n) is a must required feature for any modern web application. Internationalization enables the application to target any language in the world. Localization is a part of the Internationalization and it enables the application to render in a targeted local language. Angular provides complete support for internationalization and localization feature. Let us learn how to create a simple hello world application in different language. Create a new Angular application using below command − cd /go/to/workspace ng new i18n-sample Run the application using below command − cd i18n-sample npm run start Change the AppComponent’s template as specified below − <h1>{{ title }}</h1> <div>Hello</div> <div>The Current time is {{ currentDate | date : ”medium” }}</div> Add localize module using below command − ng add @angular/localize Restart the application. LOCALE_ID is the Angular variable to refer the current locale. By default, it is set as en_US. Let us change the locale by using in the provider in AppModule. import { BrowserModule } from ”@angular/platform-browser”; import { LOCALE_ID, NgModule } from ”@angular/core”; import { AppComponent } from ”./app.component”; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [ { provide: LOCALE_ID, useValue: ”hi” } ], bootstrap: [AppComponent] }) export class AppModule { } Here, LOCALE_ID is imported from @angular/core. LOCALE_ID is set to hi through provider so that, the LOCALE_ID will be available everywhere in the application. Import the locale data from @angular/common/locales/hi and then, register it using registerLocaleData method as specified below: import { Component } from ”@angular/core”; import { registerLocaleData } from ”@angular/common”; import localeHi from ”@angular/common/locales/hi”; registerLocaleData(localeHi); @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”], }) export class AppComponent { title = ”Internationzation Sample”; } Create a local variable, CurrentDate and set current time using Date.now(). export class AppComponent { title = ”Internationzation Sample”; currentDate: number = Date.now(); } Change AppComponent’s template content and include the currentDate as specified below − <h1>{{ title }}</h1> <div>Hello</div> <div>The Current time is {{ currentDate | date : ”medium” }}</div> Check the result and you will see the date is specified using hi locale. We have changed the date to current locale. Let us change other content as well. To do it, include i18n attribute in the relevant tag with format, title|description@@id. <h1>{{ title }}</h1> <h1 i18n=”greeting|Greeting a person@@greeting”>Hello</h1> <div> <span i18n=”time|Specifiy the current time@@currentTime”> The Current time is {{ currentDate | date : ”medium” }} </span> </div> Here, hello is simple translation format since it contains complete text to be translated. Time is little bit complex as it contains dynamic content as well. The format of the text should follow ICU message format for translation. We can extract the data to be translated using below command − ng xi18n –output-path src/locale Command generates messages.xlf file with below content − <?xml version=”1.0″ encoding=”UTF-8″ ?> <xliff version=”1.2″ xmlns=”urn:oasis:names:tc:xliff:document:1.2″> <file source-language=”en” datatype=”plaintext” original=”ng2.template”> <body> <trans-unit id=”greeting” datatype=”html”> <source>Hello</source> <context-group purpose=”location”> <context context-type=”sourcefile”>src/app/app.component.html</context> <context context-type=”linenumber”>3</context> </context-group> <note priority=”1″ from=”description”>Greeting a person</note> <note priority=”1″ from=”meaning”>greeting</note> </trans-unit> <trans-unit id=”currentTime” datatype=”html”> <source> The Current time is <x id=”INTERPOLATION” equiv-text=”{{ currentDate | date : ”medium” }}”/> </source> <context-group purpose=”location”> <context context-type=”sourcefile”>src/app/app.component.html</context> <context context-type=”linenumber”>5</context> </context-group> <note priority=”1″ from=”description”>Specifiy the current time</note> <note priority=”1″ from=”meaning”>time</note> </trans-unit> </body> </file> </xliff> Copy the file and rename it to messages.hi.xlf Open the file with Unicode text editor. Locate source tag and duplicate it with target tag and then change the content to hi locale. Use google translator to find the matching text. The changed content is as follows − Open angular.json and place below configuration under build -> configuration “hi”: { “aot”: true, “outputPath”: “dist/hi/”, “i18nFile”: “src/locale/messages.hi.xlf”, “i18nFormat”: “xlf”, “i18nLocale”: “hi”, “i18nMissingTranslation”: “error”, “baseHref”: “/hi/” }, “en”: { “aot”: true, “outputPath”: “dist/en/”, “i18nFile”: “src/locale/messages.xlf”, “i18nFormat”: “xlf”, “i18nLocale”: “en”, “i18nMissingTranslation”: “error”, “baseHref”: “/en/” } Here, We have used separate setting for hi and en locale. Set below content under serve -> configuration. “hi”: { “browserTarget”: “i18n-sample:build:hi” }, “en”: { “browserTarget”: “i18n-sample:build:en” } We have added the necessary configuration. Stop the application and run below command − npm run start — –configuration=hi Here, We have specified that the hi configuration has to be used. Navigate to http://localhost:4200/hi and you will see the Hindi localised content. Finally, we have created a localized application in Angular. Print Page Previous Next Advertisements ”;