Must Need VSCode extensions for Angular Development.

Here I listed the most unique , useful & must need VSCode extensions for Angular development.

With my experience and the plugins I used, Here I listed the most unique , useful & must need VSCode extensions for Angular development.

Must Need VSCode extension for Angular Development.

JSON2TS

JSON2TS is a really cool and effective extension which convert a JSON into TS interface object by simply copy & pasting the API response or API URL.

This will be more effective if you are playing with a huge JSON object responce.

cmd+alt+V or ctrl+alt+V. - Copy the JSON content and paste inside
the interface file with the mentioned shortcut.
(Rename the interface if required)

cmd+alt+X or ctrl+alt+X. - Copy the API URL and paste inside
the interface file with this shortcut

angular2-switcher

You can switch between the HTML, TS, Specs, CSS files of the respective component rapidly using simple keyboard shortcuts after adding this extension.

alt+o(Windows) shift+alt+o(macOS)if on .ts|.css|.spec.ts: go to html
if on .html: go to previous

alt+i(Windows) shift+alt+i(macOS)if on .ts|.html|.spec.ts: go to css
if on .css: go to previous

alt+u(Windows) shift+alt+u(macOS)if on .css|.html|.spec.ts: go to ts
if on ts: go to previous

alt+p(Windows) shift+alt+p(macOS)if on .ts|.css|.html: go to spec.ts
if on .spec.ts: go to previous

Angular Language Service

This is another effective extension which assist you in auto suggest variable in template file (HTML) which are declared in TS.

As you can access the TS declarations inside the HTML template which result in preventing variables mismatch & saves more time as you need not go back and refer the TS file for declaration.

Angular v7 Snippet

This extension helps you in unfold the complete code snippet by typing part of it. Really helpful if you don’t want to type the snippet by yourself altogether.

Other Extensions

TSLint – To find & fix the lint error on the go. This will align with your TSLint configuration.

Sass – Intended Sass autocomplete, snippet & prettifier.

Bracket Pair Colouriser – To identify the matching brackets with colors.

These are the extensions which I mostly use with VS code while developing the Angular application. The comment section is open to sharing the name of your favorite and recommended plugins which increase productivity on angular development.

Set the Default Value to Select in Angular 5 iterated with Array of Objects

Here, the simple and easy way to set default value to select in Angular 5 which is iterated with an array of objects.

Let’s consider the below sample object which is going to iterate in the select options

[
      {
		"userName": "User1",
		"userId": "1",
		"userRole": "admin"
	},
	{
		"userName": "User2",
		"userId": "2",
		"userRole": "moderator"
	},
	{
		"userName": "User3",
		"userId": "3",
		"userRole": "user"
	}
]

In above array, I need to iterate and get the complete object on selection. So I assign the complete object to the [ngValue] to the iterative option tag.

While changing the option you will get the proper object’s value, but in case of retrieving & reassign the data or initialize some value to the select dropdown as default, we cant able to straightaway do that by assigning the appropriate object to the select’s ngModel.

Solution to set default value to select in Angular 5.

HTML :

For that, we can use [compareWith].  Refer the below HTML code snippet having the [compareWith ] directive.

 <select [compareWith]="compareByuserId" [(ngModel)]="selectedUser" name="user" (change)="setUserData(selectedUser)">
    <option disabled value="undefined" > Select User</option>
    <ng-container *ngIf="users" >
       <option *ngFor=" let user of users" [ngValue]="attribute" >{{user.userName}} </option >
     </ng-container >
</select >

TypeScript:

Add the below-given code snippet to your respective TS file. Here userId is the key which used to compare the available and assigned object. You can change the key on demand.

 compareByuserId(arg1, arg2) {
    if (arg1 && arg2) {
      return arg1.userId== arg2.userId;
    } else {
      return false;
    }
  }

Retrieve & Assign Value:

Now you can directly assign the required object to the ngModel selectedUser.

This will make the select box to have the assigned value as the preselected as default.

Assign the undefined to selectedUser have the select box to have the “Select User” as a default selection.

Tune In for more Angular updates.

Consolidated list of angular cli commands

Using angular cli commands you can easily scaffold and build the angular application. Here I list and discuss the commands available in angular cli. As you know Angular development approach changes and the architecture got numerous improvements after the latest release.  Along with that the angular/cli also upgrade to support the modern angular javascript framework.

angular cli commands

angular/cli

angular/cli is a tool that helps you to start, build and test you angular application easily. angular/cli uses several commands to initialize, scaffold and maintain the application. Let’s see the most commonly used commands while creating the angular application. Before starting you need to install the angular/cli package.

Note:npm uninstall -g angular-cli @angular/cli && npm cache clean && npm install –save-dev @angular/cli@latest

Consolidated list of angular cli commands

angular/cli action

Command

Shortened

New Applicationng new app-nameng new app-name
Create Componentng generate component component-nameng g c component-name
Create Directiveng generate directive directive-nameng g d directive-name
Create Pipeng generate pipe pipe-nameng g p pipe-name
Create Serviceng generate service service-nameng g s service-name
Create Classng generate class class-nameng g cl class-name
Create Guardng generate guard guard-nameng g g guard-name
Create Interfaceng generate interface interface-nameng g i interface-name
Create Enumng generate enum enum-nameng g e enum-name
Create Moduleng generate module module-nameng g m module-name
Lint using tslintng lintng lint
Build & run unit testng testng test
Run end to end testng e2eng e2e
Compile application to output Dirng build (–dev/–prod)ng build (–dev/–prod)
Eject app and create proper webpack configuration and script bundleng ejectng eject
Extract localization i18n message from templateng xi18nng xi18n
Build and start web serverng serveng serve

The above mentioned are the basic angular/cli commands. You can also use options as a parameter along with the commands to narrow down the required behavior of cli.

Understanding Webpack Configuration – [simplified]

Understanding webpack configuration with example codes is much easier than a detailed paragraph. Recently  Angular [Latest version] also use webpack for bundle the application. You can use webpack with any of the latest  Javascript libraries like react to bundle the application.

Here I add webpack configuration file and explain the concept and configuration behind that. Before that, I start with small heads up on webpack.

webpack configuration

Webpack is a module bundler for the modern javascript application, which bundles all the dependencies required by the application. Unlike Grunt or Gulp, This will process your application and build the dependency graph and make those dependencies into a smaller bundle. Finally, this gives a processed bundles as javascript which needs to be loaded by the application.

Webpack Configuration 

All the configuration are object available under the module.exports object.

module.exports = {
....
}

There are four important basic key configurations in webpack

Entry:

Configuration options determine the entry point dependency graph of the module bundle.

Output:

configuration options determine the output bundle path and its name.

Module Loaders :

As webpack only understand Javascript all the assets need to be bundled inside the webpack. These loader and rules are responsible for those actions.

Plugins :

This adds custom functionality to the modules at compilation. Most of the plugins have customization via options parameter.

In the below code snippet, I added Angular Hybrid App (Angular 1 + Angular 4 ) webpack configuration.

var path = require('path');
var webpack = require('webpack');
// Webpack Plugins
var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
var autoprefixer = require('autoprefixer');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
/* Create multiple reference for different css bundle. 
   For example If you need two css bundle then create a 
   seperate reference for each */
var allCss = new ExtractTextPlugin('./styles/styles.css');
module.exports = {
/* Devtool is used for module debugging. multiple option string are available. The Corresponding string is to debug the original source code */
    devtool: 'inline-cheap-module-source-map',
/* Output configuration specifies the output file destination and the name. These name get the value from entry configuration */
    output: {
        path: root('./min'),
        publicPath: '',
        filename: '[name].js',
        chunkFilename: '[id].chunk.js'
    },
/* Webpack bundles the file related to the dependency graph. This entry configuration is the starting point of that dependency graph. Mostly it is the first file to kick off application. You can also give multiple entries to create a multiple bundle.
Output takes the file name from the entry objects key */
    entry: {
        'polyfills': './app/polyfills.ts',  // Output polyfill.js
        'vendor': ['./app/vendor.ts'],      // vendor.js
        'app': './app/main.ts'              // app.js
    },

/* The resolver used to find the module code that needs to be included in the bundle for every such require/import statement */
 
    resolve: {
         extensions: ['.ts', '.js', '.json', '.css', '.scss', '.html'],
         alias: {
             'npm': __dirname + '/node_modules'
            }
    },
/* Module determine how the different types of modules inside the application need to be treated */
    module: {
/* rules are array of objects used to determine how the modules need to be treated with appropriate loaders created with the help of loaders */
        rules: [
            // The files with js extension are compiled using babel-loader and added to webpack's main bundle. exclude is used to skip the un wanted files. 
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                }
            }, 
         // Files with ts extension are compiled  using awesome-typescript-loader
          {
                test: /\.ts$/,
                loaders: [{
                    loader: 'awesome-typescript-loader',
                    options: {
                        configFileName: 'tsconfig.json'
                    }
                }, 'angular2-template-loader']
            }, 
            // HTML are bundled using html-loader 
           {
                test: /\.html$/,
                loader: 'html-loader'
            }, 
           // other required application assets are bundled using normal file-loader
            {
                test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
                loader: 'file-loader?name=assets/[name].[hash].[ext]'
            }, 
            // As am using the scss here am using sass-loader for compiling and convert it into css. fallback is a kind os default loader used to bundle the css files.
            {
                test: /\.s?css$/,
                loader: allCss.extract({
                    fallback: "style-loader",
                    use: ['css-loader', 'sass-loader'],
                    allChunks: true,
                    publicPath: "./min"
                })
            }


        ]
    },
/* Plugins */ 
    plugins: [
        /* Extract text plugin reference used to seperate the css from the webpack bundle. If you have multiple reference call all the variable reference name separated by ',' */
        allCss,
        
        // Workaround for angular/angular#11580
        new webpack.ContextReplacementPlugin(
            // The (\\|\/) piece accounts for path separators in *nix and Windows
            /angular(\\|\/)core(\\|\/)@angular/,
            root('./', 'app'), // location of your src
            {} // a map of your routes
        ),
/*The CommonsChunkPlugin is an opt-in feature that creates a separate file (known as a chunk), consisting of common modules shared between multiple entry points */
        new webpack.optimize.CommonsChunkPlugin({
            name: ['app', 'vendor', 'polyfills']
        }),
/* The HtmlWebpackPlugin simplifies creation of HTML files to serve your webpack bundles */
        new HtmlWebpackPlugin({
            template: 'index.html'
        }),
        new ExtractTextPlugin('[name].css'),
    ],
/* dev server configuration */
    devServer: {
        historyApiFallback: true,
        stats: 'minimal'
    }
};
// Custom Helper functions
function root(args) {
    args = Array.prototype.slice.call(arguments, 0);
    return path.join.apply(path, [__dirname].concat(args));
}

 

Note: all the required loaders, plugin needs to be installed before use ( npm install loader-name –save-dev)

See Also: Know Basic TypeScript Features Before Starting Angular

How To Send Push Notification In Ionic Android App

In this tutorial, I am going to explain how to send Push Notification in Ionic Apps in a simple and more efficient way. Here am using Firebase Cloud Messaging (Google Cloud Messaging) for Android push notification and OneSignal to manage more segments for push notification to users and various platforms. You can integrate OneSignal with various platforms to push Notification.

This tutorial written for ionic 2 and above but still ionic 1 and cordova projects can follow same steps except sdk installation for send push notification.

send push notification

Send push notification to you hybrid ionic app in 10 simple steps

Step 1: Create Firebase account

Create Firebase account from https://firebase.google.com and Create a new project. Use your App Name for easier identification.

Step 2: Navigate to Project Settings

Once the project is created, go to the project click Settings icon and Navigate to Project Settings.

 

Step 3: Get Server Key and Sender ID

In the Settings page, Navigate to Cloud Messaging tab to get Server Key and Sender ID. Copy Both keys and save in secure place. We need this key to configure OneSignal platform.

Step 4: Create OneSignal Account

Now Create OneSignal account from https://onesignal.com and Create a new app. Use your App Name for easier identification.

 

Step 5: Select Platform in OneSignal

Now Select Android platform from the list and Click Next. You will be prompted to insert your Server Key and Sender ID.

Paste the Value which we copied from firebase in Step 3 and Click Next.

Step 6: Select SDK

Select the SDK of our Project. Currently, here we have to select Ionic/Cordova/Phonegap and Click Next.

 

Step 7: Install OneSignal SDK

OneSignal will generate App Id for the app. Now its time to install OneSignal SDK in our Ionic app.

$ ionic cordova plugin add onesignal-cordova-plugin

$ npm install --save @ionic-native/onesignal

After plugin installed, now add a plugin to your App Modules file “App.Module.ts”.

...

import { Onesignal} from '@ionic-native/onesignal';

...

@NgModule({
  ...

  providers: [
    ...
    Onesignal
    ...
  ]
  ...
})
export class AppModule { }

Step 8 : Configure “app.component.ts”

Usage

Let’s Initiate OneSignal and Subscribe the Device to OneSignal Service. Use the following code in “app.component.ts” file. Replace OneSignal App Id and Firebase Sender ID in the following code.

import { OneSignal } from '@ionic-native/onesignal';

constructor(private oneSignal: OneSignal) { }

...
//Replace APP ID and Sender ID
this.oneSignal.startInit('', '');

//Type of Alert
this.oneSignal.inFocusDisplaying(this.oneSignal.OSInFocusDisplayOption.InAppAlert);

//Handle Event when push notification is received when app is running foreground 
this.oneSignal.handleNotificationReceived().subscribe(() => {
 // do something when notification is received
});

//Handle Event When user clicks on the push notification
this.oneSignal.handleNotificationOpened().subscribe(() => {
  // do something when a notification is opened
});

//Subscription Initialized Successfully.
this.oneSignal.endInit();

More OneSignal functions available here https://ionicframework.com/docs/native/onesignal/

Step 9: Add Android Support repository

Make Sure your Android SDK installed with Android Support Repository and Google Repository.

Step 10: Trigger Push notification to your App

Build your app and Go to OneSignal page and click registered devices and Try Sending One.

Note: If you receive push notification when app is opened and app running in background but not when the app is closed. Then the problem is your device custom ROM terminates the GCM to save battery. Make the app trusted or add to the auto startup.

See also: How to post feeds on Facebook from Mobile App

Know Basic TypeScript Features Before Starting Angular

TypeScript isn’t completely a new language, it is a super script of ES6 (ECMA script 6) and it is an official collaboration between Microsoft & Google. ES6 is an advanced version of ES5 ( regular javascript).   TS or ES6 is not completely supported by all the browsers as of now. So avoid this incompatibility we need transpilers to convert the TypeScript / Es6 into ES5 which is commonly supported by all the browsers. TypeScript team developed its own transpiler. There are some transpilers are available apart from TypeScript transpiler.

typescript

Here the diagram shows the relation between the ES5, ES6 & Typescript. You can also use ES5 code in TypeScript it is completely valid code as It is a superset of ES5.

typescript

Five big improvements that TypeScript bring over ES5:

TS is more popular than ever,  due to its usability in latest Angular development. There are lots of reasons to use TS over ES5, here I list some of the important key features.

  • Types
  • Classes
  • Decorators
  • imports / Export
  • Language utilities.

Types

The major improvement over ES5 in TS is typing system. Typeig system gives the language its name. Most of the developers consider that lack of type checking in ES5 as an advantage. But let’s give it a try.

Advantages of using Types.

  • Avoid compile time errors 
  • Increase Code readability and make clear to others about your intention. 

The syntax of declaring variable name implies from the ES5 but here you optionally provide the data type along with the variable name.

ES5:

var variableName;

TS : 

var variableName : srting;
var variableName : number; 
var functionName ( args1 : string , args2 : number,args3 : boolean) : boolean{ return true; }

TS Error:

var functionName ( args1 : string , args2 : number,args3 : boolean) : boolean{
    return 12;
}

This code block return compiler error as function expecting boolean but it returning number. 

Using types will sure save us from lots of bugs. Let’s dig deeper on available built-in types.

Available Built-in Types

  • string
  • number
  • boolean
  • array

As array is a collection of object we need to mention the type objects

var variableName : Array<string>  = ['icodefy','imacify','igamefy'];
var variableName : string[]  = ['icodefy','imacify','igamefy'];

Similar with numbers.

  • Enums
  • Void – return nothing
  • Any – Default type. You can omit this

Classes

ES5 OOP’s is accomplished by using the prototype based object. These models rely on prototypes instead of classes. After compensating the lack of classes. Finally, ES6 has its own built-in classes.

To define the class you have to use “class” key word along with its class name. The class may have properties, methods, and constructors.

class class_name {
....
}

Property – defines the data attached to an instance of the class.

class car {
  name:string;
  seating : number;
  fuelType : string;
}

Methods – Function that runs in the context of the class.

To call a method inside the class we first need to create a new instance of that class object using “new” keyword

class car {
    name:string;
    seating : number;
    fuelType : string;
}
getCarName(){
   return this.name;
}  

If you have a look into that function we must access the name using the “this” keyword.

When methods do not declare any type then it assumes as “Any“. If the method is not returning any value then you need to specify the type as “void“.

As I above mention if you want to access the getCarName method you need an instance of the class object.

//Declare the object type
var c = car;
//Create new instance for car
c = new car();

//Assign data to created new instance c
c.name = "BMW X1";
c.seating = 4;
c.fuelType = "petrol";
//calling the method
console.log(c.getCarName());

Notice , you can declare the variable and instance it in a single line also

var c : car = new car();

Constructors – Special method executed when a new instance of the class is calling.

If the class doesn’t have explicitly declared constructor then it will generate by its own.

class car{
}
var c : car = new car()

Is same as

class car{
 constructor(){
 }
}
var c : car = new car();

Constructors can take parameters which help of passing the value at the time of new instance creation.

class car {
    name:string;
    seating : number;
    fuelType : string;
}
//Constructor Parameters 
constructor(name:string, seating:number,fuelType:string){
this.name = name;
this.seating : seating;
this.fuelType:fuelType;
}

getCarName(){
   return this.name;
}

Finally, the constructor makes our new class declaration bit simpler. Refer the current code with the previous example of creating the class and assign the value.

var c :car = new car('BMW X1',4,'petrol')

Inheritance

Inheritance is one of the important features of OOP’s. It refers to the property inherited by the child from its parent class. TS completely support inheritance which is achieved through “extends” keyword. Then we can modify and override inherited property.

class car {
    name:string;
    seating : number;
    fuelType : string;
}
getCarName(){
   return this.name;
}  

In below snippet, we are overriding the getCarName function.

class luxuryCar extends car {
    name:string;
    seating : number;
    fuelType : string;
getCarName(){
   return "Name : " + this.name ;
}  
}
  var c :luxuryCar = new luxuryCar('BMW X1',4,'petrol')
  console.log(c.getCarname());
//Result - Name : BMW X1

Language Utilities

Fast Arrow Function

Fast arrow function is the shorthand notation of writing functions.

ES5:

var carName = ["Volvo v90", "BMW x1"]

carName.forEach(function(name){
console.log(name)
});

the same can be rewritten in TS as shown below

TS: 

var carName = ["Volvo v90", "BMW x1"]

carName.forEach( (name) =>  console.log(name)) ;

Paranthesis are optional if function have single statement

Arrow functions clean up the inline function and make it even easier while using high order functions.

Template Strings

Template string is the most powerful feature included in ES6. Using this you can add variable and HTML tags to the string. Template string is quoted inside the back tick  “`”.  Along with the variable usage in template string, you can also include multi line strings.

var carName = 'Volvo v90';

var templateString = ` <div>
<h2> Featured Cars</h2>
<p> New Arival ${carName} </p>
</div>`;

Decorators

The decorator is a special kind of additional property attached to a class, method or a property. We use decorators with syntax “@expression“. Where expression is the function that called at the time of runtime with information about the decorator.

function func1() {
    console.log("func1(): evaluated");
    return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
        console.log("func1(): called");
    }
}

function func2() {
    console.log("func2(): evaluated");
    return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
        console.log("func2(): called");
    }
}

class Car {
    @func2()
    @func2()
    method() {}
}

Import & Export

The relationships between modules are specified in terms of imports and exports at the file level. This helps to Import and export the declarations between the modules.Modules import one another using a module loader. At runtime, the module loader is responsible for locating and executing all dependencies of a module before executing it.

 export class SearchRankComponent implements OnInit {
  @Input() search : searchRank;
  constructor() {  
  }

  ngOnInit() {
  }

  upVote():boolean{
    this.search.upVote();
    return false;
  }
  downVote():boolean{
    this.search.downVote();
    return false;
  }
import { things } from wherever
import { enableProdMode } from '@angular/core';

Destructuring

Name derived from the word de-structuring, which means breaking up of structures.

var obj = { x: 0, y: 10, width: 15, height: 20 };

// Destructuring assignment
var {x, y, width, height} = obj;
console.log(x, y, width, height); // 0,10,15,20

obj.x = 10;
({x, y, width, height} = obj); // assign to existing variables using outer parentheses
console.log(x, y, width, height); // 10,10,15,20

If destructuring is not there we have to pick off the values one by one in obj.

And that’s it! You are ready with the basic understanding of typescript and ES6 features.

 

Upgrade Application from Angular 2 to Angular 4

Angular 2 to Angular 4 upgrade is much easier than you imagine. Minimal changes in your package.json and tsconfig.json is enough to run your app developed in angular 2.  As Angular has backward compatibility which runs previous release apps in the new upgraded version.

angular 2 to angualr 4

Angular 2 to Angular 4

Pakage.json changes

angular 2 to angular 4

For upgrade, just change the “Dependencies” & “devDependencies ” portion of the package.json

Upgraded Package.json content.

"dependencies": {
        "@angular/common": "^4.0.0",
        "@angular/compiler": "^4.0.0",
        "@angular/core": "^4.0.0",
        "@angular/forms": "^4.0.0",
        "@angular/http": "^4.0.0",
        "@angular/platform-browser": "^4.0.0",
        "@angular/platform-browser-dynamic": "^4.0.0",
        "@angular/router": "^4.0.0",
        "core-js": "^2.4.1",
        "rxjs": "^5.2.0",
        "systemjs": "^0.19.47",
        "zone.js": "^0.8.5"
    },
    "devDependencies": {
        "@types/node": "^6.0.60",
        "concurrently": "^3.1.0",
        "lite-server": "^2.3.0",
        "typescript": "^2.2.2"
    }

tsconfig.json changes:

angular 2 to angular 4

Upgraded tsconfig.json content

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  }
}

Clean your node_module directory after altering the package & tsconfig files.

Run the below command in the node root directory which will make your Angular 2 application up and run in Angular 4 framework.

npm install && npm update && npm start

Key points for Angular 4 development

  • Don’t use extends onInit event or with any life cycle event.
  • Don’t use DefaultIterableDiffer,KeyValueDiffers#factories or IterableDiffers#factories.
  • Don’t use deep import as it is not a part of public API.
  • Don’t use Renderer.invokeElementMethod as it is removed. (No replacement as of now).
  • Rename template tag to ng-template.
  • Replace OpaqueTokens with InjectionTokens.
  • Remove ChangeDetectorRef argument from DifferFactory.create(…).
  • Replace ngOutletContext with ngTemplateOutletContext.
  • Replace CollectionChangeRecord with IterableChangeRecord.
  • Import BrowserAnimationsModule if you are using animation in your application.
  • Replace RootRenderer with RendererFactoryV2.
  • By default, novalidate will add to the FormModule. To revoke the native behavior add ngNoForm / ngNativeValidate.

Finally, now you are good to go with Angular 4.