Angular 8 – Discussion

Discuss Angular 8 ”; Previous Next 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. Print Page Previous Next Advertisements ”;

Angular 8 – Backward Compatibility

Angular 8 – Backward Compatibility ”; Previous Next Angular framework provides maximum compatibility with previous versions. If Angular Team deprecate a feature in a release, it will wait for 3 more release to completely remove the feature. Angular Team release a major version for every six months. Every version will have active maintenance period of six months and then Long Term Support (LTS) period for another one year. Angular does not introduce breaking changes during these 18 months. If Angular version deprecate a feature in version 5, then it will probably remove it in version 8 or in next releases. Angular maintains documentation and guides of all version. For example, Angular documentation for version 7 can be checked @ https://v7.angular.io. Angular also provides a detailed upgrade path through https://update.angular.io/ site. To update Angular application written from previous version, use below command inside the project directory: ng update @angular/cli@8 @angular/core@8 Let us see some of the important changes introduced in Angular 8. HttpModule module and its associated Http service is removed. Use HttpClient service from HttpClientModule module. /deep/, >>> and :ng-deep component selectors are removed. Angular default version of TypeScript is 3.4. Node version supported by Angular is v10 and later. @ViewChild() and ContentChild() decorator behaviour is changed from dynaic to static. Lazy loading string syntax in router module is removed and only function based is supported. loadChildren: ”./lazy/lazy.module#LazyModule” loadChildren: () => import(”./lazy/lazy.module” Print Page Previous Next Advertisements ”;

Angular 8 – Testing

Angular 8 – Testing ”; Previous Next Testing is a very important phase in the development life cycle of an application. It ensures an application quality. It needs careful planning and execution. Unit Test Unit testing is the easiest method to test an application. It is based on ensuring the correctness of a piece of code or a method of a class. But, it does not reflect the real environment and subsequently. It is the least option to find the bugs. Generally, Angular 8 uses Jasmine and Karma configurations. To perform this, first you need to configure in your project, using the below command − ng test Now, you could see the following response − Now, Chrome browser also opens and shows the test output in the “Jasmine HTML Reporter”. It looks similar to this, End to End (E2E) Testing Unit tests are small, simple and fast process whereas, E2E testing phase multiple components are involved and works together which cover flows in the application. To perform e2e test, type the below command − ng e2e You could see the below response − Print Page Previous Next Advertisements ”;

Service Workers and PWA

Angular 8 – Service Workers and PWA ”; Previous Next Progressive web apps (PWA) are normal web application with few enhancements and behaves like a native application. PWA apps does not depends on network to work. PWA caches the application and renders it from local cache. It regularly checks the live version of the application and then caches the latest version in the background. PWA can be installed in the system like native application and shortcut can be shown in the desktop. Clicking the shortcut will open the application in browser with local cache even without any network available in the system. Angular application can be converted into PWA application. To convert an Angular application, we need to use service worker API. Service worker is actually a proxy server, which sits in between the browser, application and the network. Service workers is separate from web pages. It does not able to access DOM objects. Instead, Service Workers interact with web pages through PostMessage interface. PWA application has two prerequisites. They are as follows, Browser support − Even though lot of browser supports the PWA app, IE, Opera mini and few other does not provides the PWA support. HTTPS delivery − The application needs to be delivered through HTTPS protocol. One exception of the https support is localhost for development purpose. Let us create a new application and convert it into PWA application. Create a new Angular application using below command − cd /go/to/workspace ng new pwa-sample Add PWA support using below command − cd pwa-sample ng add @angular/pwa –project pwa-sample Build the production version of the application, ng build –prod PWA application does not run under Angular development server. Install, a simple web server using below command − npm install -g http-server Run the web server and set our production build of the application as root folder. f the application as root folder. http-server -p 8080 -c-1 dist/pwa-sample Open browser and enter http://localhost:8080. Now, go to Developer tools -> Network and select Offline option. Normal application stops working if network is set to Offline but, PWA application works fine as shown below − Print Page Previous Next Advertisements ”;

Angular 8 – Useful Resources

Angular 8 – Useful Resources ”; Previous Next The following resources contain additional information on Angular 8. Please use them to get more in-depth knowledge on this. Useful Video Courses Angular – The Complete Course 14 Lectures 48 mins Ganesh Kavhar More Detail Angular JS Full Stack: Create and Host Listing/Classified Site 59 Lectures 4 hours Jay R More Detail Full-Stack web app development with Angular 12, .NET Core Web API & Mongo DB Most Popular 20 Lectures 49 mins Vinay Kumar More Detail Angular 12, .NET Core Web API & Microsoft SQL Full Stack Web Development 21 Lectures 55 mins Vinay Kumar More Detail Angular 12, .NET Core Web API and MySQL Web Development 21 Lectures 51 mins Vinay Kumar More Detail Angular 12, .NET Core Web API & PostgreSQL Full Stack Web Development 5 Lectures 51 mins Vinay Kumar More Detail Print Page Previous Next Advertisements ”;

Angular 9 – What’s New?

Angular 8 – What”s New? ”; Previous Next Angular community has continuosly updating its version. This chapter explains about Angular 9 version updates. Install Angular 9 If you want to work with Angular 9, first you need to setup Angular 9 CLI using the below command: npm install -g @angular/cli@^9.0.0 After executing this command, you can check the version using the below command: ng version Angular 9 Updates Let’s understand Angular 9 updates in brief. Ivy compiler Ivy compiler becomes the default compiler in Angular 9. This makes apps will be faster and very efficient. Whereas, Angular 8 Ivy is optional. We have to enable it inside tsconfig.json file. Ivy compiler supports the following features: Performs faster testing − TestBed implementation helps to test more efficient. Improved CSS class and styles − Ivy styles are easily merged and designed as predictable. Improved type checking − This feature helps to find the errors earlier in development process. Enhanced debugging − Ivy comes with more tools to enable better debugging features. This will be helpful to show useful stack trace so that we can easily jump to the instruction. Ahead-of-Time compiler − This is one of the important improvements in compiler’s performance. AOT builds are very faster.  Improved internationalization – i18n substitutions helps to build more than ten times faster than previous versions. Reliable ng update ng updates are very reliable. It contains clear progress updates and runs all of the migrations. This can be done using the below command: ng update –create-commits Here, –create-commits flag is used to commit your code after each migration. Improved Dependency Injection @Injectable service helps to add injector in your application. providedIn meta data provides new option, platform to ensure the object can be used and shared by all application. It is defined below: @Injectable({ providedIn: ”platform” }) class MyService {…} TypeScript 3.8 Angular 9 is designed to support 3.8 version. TypeScript 3.8 brings support for the below features: Type-Only Imports and Exports. ECMAScript Private Fields. Top-Level await. JSDoc Property Modifiers. export * as ns Syntax. Angular 9.0.0-next.5 Angular 9.0.0-next.5 build has small size of main.js file, which makes better performance compare to previous version of Angular 8. IDE enhancement Angular 9 provides imporves IDE supports. TextMate grammar enables for syntax highlighting in inline and external templates. Conclusion Angular is flexible, ever improving, continuously updated and dependable framework. Angular greatly simplify the process of SPA development. By providing new features in each release like Angular Universal, Progressive Web App, Web workers, Bazel build, Ivy Compiler, etc., Angular will have a long life and complete support of the front end developer. Print Page Previous Next Advertisements ”;

Angular 8 – Angular Material

Angular 8 – Angular Material ”; Previous Next Angular Material provides a huge collection of high-quality and ready-made Angular component based on Material design. Let us learn how to include Angular material in Angular application and use its component. Configure Angular Material Let us see how to configure Angular Material in Angular application. Open command prompt and go to project root folder. cd /go/to/expense-manager Add Angular material package using below command − ng add @angular/material Angular CLI will ask certain question regarding theme, gesture recognition and browser animations. Select your any theme of your choice and then answer positively for gesture recognition and browser animation. Installing packages for tooling via npm. Installed packages for tooling via npm. Choose a prebuilt theme name, or “custom” for a custom theme: Indigo/Pink [ Preview: https://material.angular.i o?theme=indigo-pink ] Set up HammerJS for gesture recognition? Yes Set up browser animations for Angular Material? Yes Angular material packages each UI component in a separate module. Import all the necessary module into the application through root module (src/app/app.module.ts) import { MatTableModule } from ”@angular/material/table”; import { MatButtonModule } from ”@angular/material/button”; import { MatIconModule } from ”@angular/material/icon”; @NgModule({ imports: [ MatTableModule, MatButtonModule, MatIconModule ] }) Change the edit button using ExpenseEntryListComponent template (src/app/expense-entry-list/expense-entry-list.component.html) as specified below − <div class=”col-sm” style=”text-align: right;”> <!– <button type=”button” class=”btn btn-primary”>Edit</button> –> <button mat-raised-button color=”primary”>Edit</button> </div> Run the application and test the page. ng serve The output of the application is as follows − Here, the application clearly shows the Angular Material button. Working example Some of the important UI elements provided by Angular Material package. Form field Input Checkbox Radio button Select Button DatePicker List Card Grid list Table Paginator Tabs Toolbar Menu Dialog Snackbar Progress bar Icon Divider Using material component is quite easy and we will learn one of the frequently used material component, Material Table by working on a sample project. Open command prompt and go to project root folder. ng add @angular/material Let us change our ExpenseEntryListComponent(src/app/expense-entry-list/expense-entry-list.component.ts) and use Material Table component. Declare a variable, displayedColumns and assign the list of column to be displayed. displayedColumns: string[] = [”item”, ”amount”, ”category”, ”location”, ”spendOn” ]; Add material table as specified below in the ExpenseEntryListComponent template (src/app/expense-entry-list/expense-entry-list.component.html) and remove our existing list. <div class=”mat-elevation-z8″> <table mat-table [dataSource]=”expenseEntries”> <ng-container matColumnDef=”item”> <th mat-header-cell *matHeaderCellDef> Item </th> <td mat-cell *matCellDef=”let element” style=”text-align: left”> {{element.item}} </td> </ng-container> <ng-container matColumnDef=”amount”> <th mat-header-cell *matHeaderCellDef > Amount </th> <td mat-cell *matCellDef=”let element” style=”text-align: left”> {{element.amount}} </td> </ng-container> <ng-container matColumnDef=”category”> <th mat-header-cell *matHeaderCellDef> Category </th> <td mat-cell *matCellDef=”let element” style=”text-align: left”> {{element.category}} </td> </ng-container> <ng-container matColumnDef=”location”> <th mat-header-cell *matHeaderCellDef> Location </th> <td mat-cell *matCellDef=”let element” style=”text-align:left”> {{element.location}} </td> </ng-container> <ng-container matColumnDef=”spendOn”> <th mat-header-cell *matHeaderCellDef> Spend On </th> <td mat-cell *matCellDef=”let element” style=”text-align: left”> {{element.spendOn}} </td> </ng-container> <tr mat-header-row *matHeaderRowDef=”displayedColumns”></tr> <tr mat-row *matRowDef=”let row; columns: displayedColumns;”></tr> </table> </div> Here, mat-table property is used to convert the normal table in to material table. [dataSource] property is used to specify the data source of the table. Material table is template based and each column can be designed using separate template. ng-container is used to create template. matColumnDef is used to specify the column of the data source applied to the particular ng-container. mat-header-cell is used to specify the header text for each column. mat-cell is used to specify the content of each column. mat-header-row and mat-row is used to specify the order of the column in row. We have used only the basic features of the Material table. Material table has many more features such as sorting, pagination, etc. Run the application. ng serve The output of the application is as follows − Print Page Previous Next Advertisements ”;

Angular 8 – Building with Bazel

Angular 8 – Building with Bazel ”; Previous Next Bazel is an advanced build and test tool. It supports lot of features suitable for large projects. Some of the features of Bazel are as follows: Support multiple languages. Support multiple platforms. Support multiple repository. Support high-level build language. Fast and reliable. Angular supports building the application using bazel. Let us see how to use bazel to compile Angular application. First, install @angular/bazel package. npm install -g @angular/bazel For existing application, Add @angular/bazel as mentioned below: ng add @angular/bazel For new application, use below mentioned command: ng new –collection=@angular/bazel To build an application using bazel, use below command: ng build –leaveBazelFilesOnDisk Here, leaveBazelFilesOnDisk option will leave the bazel files created during build process, which we can use to build the application directly using bazel. To build application using bazel directly, install @bazel/bazelisk and then, use bazelisk build command. npm install -g @bazel/bazelisk bazelisk build Print Page Previous Next Advertisements ”;

Angular 8 – Accessibility

Angular 8 – Accessibility ”; Previous Next Accessibility support is one of the important feature of every UI based application. Accessibility is a way of designing the application so that, it is accessible for those having certain disabilities as well. Let us learn the support provided by Angular to develop application with good accessibility. While using attribute binding, use attr. prefix for ARIA attributes. Use Angular material component for Accessibility. Some of the useful components are LiveAnnouncer and cdkTrapFocu. Use native HTML elements wherever possible because native HTML element provides maximum accessibility features. When creating a component, select native html element matching your use case instead of redeveloping the native functionality. Use NavigationEnd to track and control the focus of the application as it greatly helps in accessibility. Print Page Previous Next Advertisements ”;

Authentication and Authorization

Angular 8 – Authentication and Authorization ”; Previous Next Authentication is the process matching the visitor of a web application with the pre-defined set of user identity in the system. In other word, it is the process of recognizing the user’s identity. Authentication is very important process in the system with respect to security. Authorization is the process of giving permission to the user to access certain resource in the system. Only the authenticated user can be authorised to access a resource. Let us learn how to do Authentication and Authorization in Angular application in this chapter. Guards in Routing In a web application, a resource is referred by url. Every user in the system will be allowed access a set of urls. For example, an administrator may be assigned all the url coming under administration section. As we know already, URLs are handled by Routing. Angular routing enables the urls to be guarded and restricted based on programming logic. So, a url may be denied for a normal user and allowed for an administrator. Angular provides a concept called Router Guards which can be used to prevent unauthorised access to certain part of the application through routing. Angular provides multiple guards and they are as follows: CanActivate − Used to stop the access to a route. CanActivateChild − Used to stop the access to a child route. CanDeactivate − Used to stop ongoing process getting feedback from user. For example, delete process can be stop if the user replies in negative. Resolve − Used to pre-fetch the data before navigating to the route. CanLoad − Used to load assets. Working example Let us try to add login functionality to our application and secure it using CanActivate guard. Open command prompt and go to project root folder. cd /go/to/expense-manager Start the application. ng serve Create a new service, AuthService to authenticate the user. ng generate service auth CREATE src/app/auth.service.spec.ts (323 bytes) CREATE src/app/auth.service.ts (133 bytes) Open AuthService and include below code. import { Injectable } from ”@angular/core”; import { Observable, of } from ”rxjs”; import { tap, delay } from ”rxjs/operators”; @Injectable({ providedIn: ”root” }) export class AuthService { isUserLoggedIn: boolean = false; login(userName: string, password: string): Observable { console.log(userName); console.log(password); this.isUserLoggedIn = userName == ”admin” && password == ”admin”; localStorage.setItem(”isUserLoggedIn”, this.isUserLoggedIn ? “true” : “false”); return of(this.isUserLoggedIn).pipe( delay(1000), tap(val => { console.log(“Is User Authentication is successful: ” + val); }) ); } logout(): void { this.isUserLoggedIn = false; localStorage.removeItem(”isUserLoggedIn”); } constructor() { } } Here, We have written two methods, login and logout. The purpose of the login method is to validate the user and if the user successfully validated, it stores the information in localStorage and then returns true. Authentication validation is that the user name and password should be admin. We have not used any backend. Instead, we have simulated a delay of 1s using Observables. The purpose of the logout method is to invalidate the user and removes the information stored in localStorage. Create a login component using below command − ng generate component login CREATE src/app/login/login.component.html (20 bytes) CREATE src/app/login/login.component.spec.ts (621 bytes) CREATE src/app/login/login.component.ts (265 bytes) CREATE src/app/login/login.component.css (0 bytes) UPDATE src/app/app.module.ts (1207 bytes) Open LoginComponent and include below code − import { Component, OnInit } from ”@angular/core”; import { FormGroup, FormControl } from ”@angular/forms”; import { AuthService } from ”../auth.service”; import { Router } from ”@angular/router”; @Component({ selector: ”app-login”, templateUrl: ”./login.component.html”, styleUrls: [”./login.component.css”] }) export class LoginComponent implements OnInit { userName: string; password: string; formData: FormGroup; constructor(private authService : AuthService, private router : Router) { } ngOnInit() { this.formData = new FormGroup({ userName: new FormControl(“admin”), password: new FormControl(“admin”), }); } onClickSubmit(data: any) { this.userName = data.userName; this.password = data.password; console.log(“Login page: ” + this.userName); console.log(“Login page: ” + this.password); this.authService.login(this.userName, this.password) .subscribe( data => { console.log(“Is Login Success: ” + data); if(data) this.router.navigate([”/expenses”]); }); } } Here, Used reactive forms. Imported AuthService and Router and configured it in constructor. Created an instance of FormGroup and included two instance of FormControl, one for user name and another for password. Created a onClickSubmit to validate the user using authService and if successful, navigate to expense list. Open LoginComponent template and include below template code. <!– Page Content –> <div class=”container”> <div class=”row”> <div class=”col-lg-12 text-center” style=”padding-top: 20px;”> <div class=”container box” style=”margin-top: 10px; padding-left: 0px; padding-right: 0px;”> <div class=”row”> <div class=”col-12″ style=”text-align: center;”> <form [formGroup]=”formData” (ngSubmit)=”onClickSubmit(formData.value)” class=”form-signin”> <h2 class=”form-signin-heading”>Please sign in</h2> <label for=”inputEmail” class=”sr-only”>Email address</label> <input type=”text” id=”username” class=”form-control” formControlName=”userName” placeholder=”Username” required autofocus> <label for=”inputPassword” class=”sr-only”>Password</label> <input type=”password” id=”inputPassword” class=”form-control” formControlName=”password” placeholder=”Password” required> <button class=”btn btn-lg btn-primary btn-block” type=”submit”>Sign in</button> </form> </div> </div> </div> </div> </div> </div> Here, Created a reactive form and designed a login form. Attached the onClickSubmit method to the form submit action. Open LoginComponent style and include below CSS Code. .form-signin { max-width: 330px; padding: 15px; margin: 0 auto; } input { margin-bottom: 20px; } Here, some styles are added to design the login form. Create a logout component using below command − ng generate component logout CREATE src/app/logout/logout.component.html (21 bytes) CREATE src/app/logout/logout.component.spec.ts (628 bytes) CREATE src/app/logout/logout.component.ts (269 bytes) CREATE src/app/logout/logout.component.css (0 bytes) UPDATE src/app/app.module.ts (1368 bytes) Open LogoutComponent and include below code. import { Component, OnInit } from ”@angular/core”; import { AuthService } from ”../auth.service”; import { Router } from ”@angular/router”; @Component({ selector: ”app-logout”, templateUrl: ”./logout.component.html”, styleUrls: [”./logout.component.css”] }) export class LogoutComponent implements OnInit { constructor(private authService : AuthService, private