Posts

Showing posts from 2021

Model Mapper in Angular

Hi Friends, This is Lakshman here. As part of the Series "Angular Best Practices". Today, We will Model Mapper in Angular . Pre-requisites: The pre-requisites are Node.JS - Click Here Angular CLI - Click Here VS Code - Click Here Model Mapper It's a concept build based on AutoMapper from C#. While integrating with API, When we were required to map property. The Model Mapper requires Two things to do, ModelMapper Class PropertyMap Function. The ModelMapper class file as below, export class ModelMapper<T> { _propertyMapping: any; _target: any; constructor(type: { new(): T }) { this._target = new type(); this._propertyMapping = this._target.constructor._propertyMap; } map(source: any) { Object.keys(this._target).forEach((key) => { const mappedKey = this._propertyMapping[key]; if (mappedKey) { this._target[key] = source[mappedKey]; } else { this._target[key] = source[key]; } });

Tips & Tricks In Angular

Hi Friends, This is Lakshman here. As part of the Series "Angular Best Practices". Today, We will Tips & Tricks in Angular . Pre-requisites: The pre-requisites are Node.JS - Click Here Angular CLI - Click Here VS Code - Click Here Now, we are going to see some Tips & Tricks in Angular. Tip No 1: Stable our packages For machine critical applications, we need to stable our packages with a tilde(~) as below, ... "ng-block-ui": "~3.0.2", "rxjs": "~6.5.5", "tslib": "~2.0.0", "uuid": "~8.3.2", "zone.js": "~0.10.3" ... Tip No 2: Use npm audit weekly Nowadays, npm Packages may be deprecated or consist of some vulnerabilities. So we need to audit our package on a weekly or monthly basis via the below commands, npm audit To Fix packages run below command, npm audit fix If you want to enforce all the changes, add --force like below, npm audit fix --f

RxJS Subject In Angular

Hi Friends, This is Lakshman here. As part of the Series "Angular Best Practices". Today, We will RxJS Subject in Angular . Pre-requisites: The pre-requisites are Node.JS - Click Here Angular CLI - Click Here VS Code - Click Here RxJS Subject A Subject is like an Observable, Where we can subscribe to information and receives it when new data is available. Now, we are going to see how we could use Subject in Angular. Sent Info between Components. At First, we need a service to define our Subject as below, import { Observable, Subject } from 'rxjs'; private infoSubject = new Subject<any>(); Then we need to set up the method to get Observable, Send and Clear Info as below, import { Observable, Subject } from 'rxjs'; ... onInfo(): Observable<any> { return this.infoSubject.asObservable(); } sendInfo(info: any) { if (info !== undefined) { this.infoSubject.next(info); } } clearInfo() { this.infoSubject.next();

Class WorkAround in Angular

Hi Friends, This is Lakshman here. As part of the Series "Angular Best Practices". Today, We will Class WorkAround in Angular . Pre-requisites: The pre-requisites are Node.JS - Click Here Angular CLI - Click Here VS Code - Click Here Class As predominantly angular uses class on many ways such as Modules, Components, Service & lot. Now, we are going to see how we could use Class in Angular. Class WorkArounds Let us see some workaround, 1. Class Vs Interface We need to use a class instead of an interface. When we use an interface, it needs to declare its property whenever we create an instance. If we use class, we may use a constructor to set default values and set properties for class, as below, export interface <InterfaceName> { <property1>: string; <property-2>: string; } export class <ClassName> implements <InterfaceName> { <property1>: string; <property-2>: string; constructor() {

Master-Child in Angular App

Hi Friends, This is Lakshman here. As part of the Series "Angular Best Practices". Today, We will Master-Child in Angular App . Pre-requisites: The pre-requisites are Node.JS - Click Here Angular CLI - Click Here VS Code - Click Here Check this out To understand how to Structure your Angular App - click here Master-Child On every application, the master-child concept will exist because it's a traditional approach to flow data. In Angular to implement it, we have two decorators, @Input @Output These decorators will be declared only on the child component, where the master send input and receive output. Such code will look like below, //#region Input Variables @Input() todo: Todo; @Output() todosEvent = new EventEmitter<Todo[]>(); //#endregion To Send and receive information from Master , use it like angular default properties as below, <app-todo-entry [todo]="todo" (todosEvent)="rtnTodoList($event)"></ap

Routing in Angular App

Hi Friends, This is Lakshman here. As part of the Series "Angular Best Practices". Today, We will Routing in Angular App . Pre-requisites: The pre-requisites are Node.JS - Click Here Angular CLI - Click Here VS Code - Click Here Check this out To know how to Handle Back-Forth Page Routing - click here To understand how to Structure your Angular App - click here Route There are certain things to remember when creating routing, At First, we need to place our routing module at the end of the imports array like below, imports: [ BrowserModule, HttpClientModule, BlockUIModule.forRoot(), // Import BlockUIModule ... AppRoutingModule ], If not, your routing may break your application routing flow. Make use of all elements as required as possible. Some properties as below, data Helps to send data to the component via routing resolve Helps to retrieve or fetch data required for component via API. canActivate Helps to restrict page

Debug Angular App

Image
Hi Friends, This is Lakshman here. As part of the Series "Angular Best Practices". Today, We will Debug Angular App . Pre-requisites: The pre-requisites are Node.JS - Click Here Angular CLI - Click Here VS Code - Click Here VS Code Debug for Chrome Extenstion - Click Here Angular DevTools (Chrome) - Click Here Debug App There are lot of option on debugging app, we are going to look only options below, Via Debug For Chrome VS Code Extension Via DevTools (All Browser) Angular DevTools Browser Extension Do's Always Place Checkpoint on Code or Browser to debug Evalvulate the value via Debug Console on VS Code or on Browser Dev Console. Don't Never type debugger; in any part of code. Don't use console.log to check the values. It may lead to data privacy issues. Some Snapshot Debug on VS Code with Chrome Extensions Via Chrome Extension Debug on Chrome Browser via Chrome Browser Debug via Angular

Implement Angular Reactive Forms

Hi Friends, This is Lakshman here. As part of the Series "Angular Best Practices". Today, We will Implement Angular Reactive Forms . Pre-requisites: The pre-requisites are Node.JS - Click Here Angular CLI - Click Here VS Code - Click Here For Code Editor its VS Code with Remote Container. If you want to develop inside Container - Check This Out Reactive Forms In Every Angular Application, there will be at least Form to Fill by End User. There are always two ways to implement Forms, Form . Reactive Forms . Its Benefits are Ability to create Dynamic Forms. Helps to set Validator initially while creating form via Form Group. Easy Validation Options. Implementation: Step 1: Add Dependencies Add ReactiveFormsModule in app.module.ts & respective Module File. import { ReactiveFormsModule } from '@angular/forms'; @NgModule({ ... imports: [ ... ReactiveFormsModule, ... ] }) Step 2: Add Reactive Form Builder and Form Add

Develop Angular App inside Container

Image
Hi Friends, This is Lakshman here. As part of the Series "Angular Best Practices". Today, We will Develop Angular App inside Container . Pre-requisites: The pre-requisites are Node.JS - Click Here Angular CLI - Click Here Install Docker - Click Here VS Code - Click Here Remote - Containers Click Here Once Install Docker & Node.JS install Angular CLI via NPM Package Manager. Implementation: Step 1: Setup Docker For Dev. To Setup Docker for Angular App for Development, Please refer the below, Blog - Click Here Video - Click Here As small Setups, Copy the DockerFile.dev via URL Set Start Script as below json "start": "ng serve --host 0.0.0.0" To Build run below command, powershell docker build -t <appN-name>:dev -f Dockerfile.Dev . Run the Container use below command, powershell docker run -it --rm -p 9001:4200 -v ${PWD}/src:/usr/src/app/src --name <container-name> <app-name>:dev Step 2: Setup Remote

Implement Resolver in Angular

Hi Friends, This is Lakshman here. As part of the Series "Angular Best Practices". Today, We will Implement Resolver for your angular app . Pre-requisites: The pre-requisites are Node.JS - Click Here Angular CLI - Click Here VS Code - Click Here Creeate Resolver - Click Here Angular Snippets (Version 11) Click Here For Code Editor its VS Code . Resolver In Angular Application, every page requires some information to display it. By Default, every developer call service to fetch some information to display in OnInit Function inside Component. Most people forgot about Resolver itself. It helps our application to way better than you think. Service & Resolver has to be like bread & butter to Solve Data dependencies on Page Load. Things to know By default, we have the option to Create Resolver via Angular-CLI after cli version 11.0.5 or greater. Add Angular Snippets from Extension Marketplace. Each Resolver can have only one resolve method. Things to

Implement Logging in Angular With REST API (MongoDB)

Hi Friends, This is Lakshman here. Welcome back to the Series Angular Best Practices Today, We will Implement Logging for your angular app with REST API . Pre-requisites: The pre-requisites are Node.JS - Click Here Angular CLI - Click Here Docker - Click Here MongoDB - Click Here MongoDB Compass - Click Here For Code Editor its VS Code . Implementation: We will go there the Implementation by Steps, Step 1: Create the MongoDB Database in Docker or Cloud For Docker: docker pull mongo docker run --name mongodb -p 37017:27017 -d mongo For Cloud: Click Here Preferred Option is Docker Step 2: Create Node.JS REST API with MongoDB. Fork the Repo: Click Here else Connect the API URl: https://ngangularpracticesapi.azurewebsites.net/ Step 3: Copy the MongoDB URI to .env like below, MONGO_URI = mongodb://localhost:37017/ngAngularPractices Step 4. Run the API on Local with below commands, npm run start:dev Step 5. Add Config to Environment Configuration File as below,

Implement Logging in Angular with Firebase

Hi Friends, This is Lakshman here. Welcome back to the Series Angular Best Practices Today, We will Implement Logging for your angular app . Every Application required Logging irresptive of Application. Its either Front-End or Back-End. For Back-End, we have lots of packages and SDK available for such as Serilog, Log4Net for .NET Core, Framework. However, In Front-End we need to Store your Logs somewhere in NoSQL Database where we can query the logs. Today we are going to use FireBase Cloud Database to Store our logging. As its Client-side SDK. Our other options are Application Insights (Microsoft Azure) JSLog with Seq. etc., Pre-requisites: The pre-requisites are Node.JS - Click Here Angular CLI - Click Here FireBase Account with Cloud Database - Click Here For Code Editor its VS Code. Implementation: We will go there the Implementation by Steps, Step 1: Create the Cloud FireBase Database - Click Here Step 2: Add Web Client for Project via Steps Step 3: Copy th

Dockerize Angular App for Dev

Hi Friends, This is Lakshman here. Welcome back to the Series Angular Best Practices Today, We will Dockerize your angular app for Development . Now as days, we develop application with multiple developers. Each one have there own Node.JS Environment. To Solve this issue we can containerize your application to run inside Docker. Pre-requisites: The pre-requisites are Install Docker - Click Here Node.JS - Click Here Angular CLI - Click Here Once Install Docker & Node.JS install Angular CLI via NPM Package Manager. Implementation: On your Existing Angular Application, Create a File Called Dockerfile.Dev Dev indicates for Development Docker File. Inside that Dockerfile.Dev, Copy the below code # Create a new image from the base nodejs 12.7 image. FROM node:12.7-alpine # Create the target directory in the image RUN mkdir -p /usr/src/app # Set the created directory as the working directory WORKDIR /usr/src/app # Copy the package.json inside the working directory COPY

Solve Dev-Dependency Issues

Hi Friends, This is Lakshman here. Welcome back to the Series Angular Best Practices Today, We will try to solve the some development dependencies issues. Now as days, we develop application with multiple developers. Each one have there own Node.JS Environment. So They run into dev-environment issues, such as below, npm install command not completed. Unable to build Unable to run application locally. Now we will address the issues one by one, Command npm install not completed: This will happen based on certain situation, Node.js is not properly installed. App created node.js is different from running node.js version If you app style type is scss , it occur because of node-sass issue. To Solve the Issue, Dockerize the application with Dev-Environment on code. Document the App's development procedure. If you are able to solve this issue the Unable to Build or Run App will solve automatically. On-road head, we will discuss a lot of things. Looking forward

Your-First-Angular-Testing (Part 2)

Hi Friends, This is Lakshman here. Welcome back to the Series Angular Best Practices Today, We will go through Part 2 of your First Testing in Angular App. If you do not check Part-1 Check this out Angular Testing In this blog, we will discuss the multiple options of testing Services. The Service consists of * Fetch or Post Data to get Response from API. * Common Functionality such as Validation, Data Conversion, etc., The Difficult part only for API Calls because we can't use the API directly. We need to Mock the API to get the Response. Sample Testing for Service as below, import { HttpClient } from '@angular/common/http'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { getTestBed, TestBed } from '@angular/core/testing'; import { environment } from '@env/environment'; import { TempTests } from './test.service.mockdata'; import { TestService } from './test.service';

Your-First-Angular-Testing

Hi Friends, This is Lakshman here. Welcome back to the Series Angular Best Practices Today, We will go through, how to Create you First Testing in Angular App. Angular Testing As we develop the application, we usually validate the functionality via Serving the Application and check it's working or not. What if we need to check for multiple workflows per functionality either way as Positive & Negative Scenario. As a default, it has two types of tests, Unit Testing (via Karma ) End-To-End Testing (via Protractor ) Unit Testing On Unit Testing, its available for * Components * Service In Testing, we can test the two elements such as * HTML Testing * Code Testing Testing Files will be available with extension as .spec.ts By Default, angular generate the template below, import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { HelloComponent } from './hello.component'; describe('HelloComponent', () => { let comp

Handling REST API Call in Angular

Hi Friends, This is Lakshman here. Welcome back to the Series Angular Best Practices Today, We will go through the best practices for handling REST API Call on App. REST API Call In our day-to-day development, we use REST API for below, Fetch information. Fetch information with Params. Post Data for either Create / Update / Delete. For each request, we required certain things to do. API Url HTTP Headers Content Type either XML or JSON. Authentication Token In HTTP Header Content-Type & Authentication Token is common. So we required to store in Common Service to Set it. It better to have a Function to generate Header with ContentType ContentType with Auth. So we can access it. The Function will look like below, getHeader() { const headers = new HttpHeaders({ 'Content-Type': 'application/json' }); return headers; } getHeaderAuth() { const headers = new HttpHeaders({ 'Content-Type': 'application/json

Handle Encrypt-Decrypt

Hi Friends, This is Lakshman here. Welcome back to the Series " Angular Best Practices ". Today, We will go through about handling Encryption & Decryption on App. Encrypt & Decrypt As we develop the application probably, we will store some values on Session Storage or Local Storage. For Implementing, the packages required are * crypto-js * @types/crypto-js Shown as below, "dependencies": { ... "@types/crypto-js" : "^4.0.1" , "crypto-js" : "^4.0.0" , ... } We are required to set the EncryptKey for Encrypt-Decrypt the value. It's better to configure on environment.ts file as below, export const environment = { production: false, hmr: true, version: env.npm_package_version, ... EncryptKey: '<Key for Encrypt or Decrypt Values.>', ... }; For Enryption & Decryption we have numerous options such as, * AES Encryption & Decryption * Triple DES Encryption

Handle Back-Forth Page Routing

Hi Friends, This is Lakshman here. It's been a long time since the last post, But it's good to see you all. Welcome back to the Series " Angular Best Practices ". Today, We will go through options to navigate between page back-forth page routing on App. Back-Forth Page Routing As we develop the application most probably, we will navigate between pages. The Usually Navigation options might be as below, * Header with All Navigation Option. * From Master to Detail, etc., If, our Angular App deployed as the Web Portal. The Navigation options will be the default because you can access only via Menus. What if, our angular app deployed as Mobile App. User can able to navigate not only via Page Menu and also via default back options. In this case, most probably, we may use a navigation service to maintain history. If you navigate a page via Phone's back options, it might cause an issue on the app. To Address the Issue, I have implemented the Session storage op