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

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.

Angular directive that dynamically change input box width respective to the placeholder

Recently I get with a requirement to dynamically change input box width respective to the placeholder length. Now I am going to give a small heads up about use case and how I accomplished the task.

dynamically change input box length

Mission:

This application is developed with angularJs. As it has multiple language support placeholder also changes respective to the language. For some of the language, placeholder is not fully visible and for some of the language, the input box width was too large compared to the placeholder. So here the mission is to dynamically change the width of the input box respective to the placeholder length.

Mission Accomplished.

To accomplish the above mission I create a custom directive to change the width of the input box dynamically. Here the challenge is to find the width of the placeholder. The length property of the placeholder will give you the character count. Using that we can’t able to find the element width of the placeholder text.

In this directive, I used two key things to find the width of the placeholder text

  1. Font size – this will get the current font size used in the input box
  2.  <span> – Sudo element to calculate the actual element width of the placeholder

Calculating the Font Size

The below given js code will return the font size used in the input box which invoked this directive

var fontSize = parseFloat(window.getComputedStyle(elem[0], null).getPropertyValue('font-size'));

Pseudo Element

After that dynamically create a pseudo element with the style of above identified font size because this will help us to get the exact width of the placeholder content. Once the process of identifying the width is donr then the pseudo element got removed from the DOM.

Options

minwidth – in addition, this attribute will set the minimum width for the input box

bufferwidth – in addition, this attribute will add buffer with for input box for better readability and appearance.

Angular Directive to Dynamically Adjust input box width respective to the placeholder length

Code Snippet

See the Pen Angular Directive to Dynamically Adjust input box width respective to the placeholder length by icodefy (@icodefy) on CodePen.

You can find the working snippest here. Drop your suggestion and valuble comments.

Turn Google Bar chart into Tornado Chart (Butterfly Chart)

Google chart visualization provide multiple varieties of charts to addressing your data visualization needs. The good things about the Google chart are it had lots of customization option and also it is absolutely free to integrate and use with your web application. Google chart includes lots of inbuilt customization options, these options allow you have the better visualization. Even though it doesn’t have any Tornado chart in its library. But we can customize the google bar chart into Tornado Chart with some work around.

google-bar-chart-to-tornado-chart_new

As I got unique requirement from one of the projects, which is a rating and review kind of stuff developed with HTML5 & Jquery for frontend and Laravel 5 & SQL for the backend services.

Mission

Here mission is to show the user’s top 3 positive & negative ratings in a single chart. That Chart contains most liked components on its right and most disliked element on its left along with its average rating and element name as a label. While creating it with the google bar chart the challenge we faced is to make positive and negative values bar at the same level as shown in the figure below.

Tornado butterfly Chart

Mission Accomplished

While implementing google bar chart with negative values it’s not displayed as expected. so we need a workaround to make the chart look like as expected. By default, it displays the chart as shown below with positive and negative values at different levels of the y axis.

Default  google chart with negative valuesnormal google bar chart

Work Around in Google Bar Chart

To make this default bar chart to visualize like a required Tornado chart (Butterfly Chart) we need to do some work around. I will explain those option attribute added to the default chart option.

you can refer the JS part of the code snippet below in which the variable “option” inside “drawbarChart” function holds the additional options for chart visualization.

If you refer that variable in which we added the “isStacked” attribute to make the negative and positive values at the same level

isStacked: true,

we are getting data in ascending order from backend which holds smaller value at the first. But as per the requirement, we need to show the top rated value at first in the google Tornado chart. For invert the chart value we added the another attribute to the option “vAxis” object.

vAxis: {
direction: -1 ,
}

 

Code Snippet

See the Pen Customize Google Barchart into Tornado Chart (Butterfly Chart) by icodefy (@icodefy) on CodePen.

You can find the working code snippet above. Our comment box is open. Drop your valuable comments