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.

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.

 

5 Essential Browser Plugins for Frontend Developers

Along with developer tool of chrome, I have 5 essential browser plugins which make me feel more flexible with developing and debugging the web application. I always keep these plugins to make my work easy. Most you may already come across a couple of these plugins but rest will lighten and faster your development process.

Essential Browser Plugins

Essential Browser Plugins

Colorzilla

Colorzilla is a most useful and essential browser plugin for effective color sampling which allows you to pick a color from the live page or a pallet or browse colors. Along with that Colorzilla have a web page sampler that allows you to create pallet group that is used in the sampled web page. Colorzilla also has the css gradient generator which automatically generates the css code for the designed gradient.

Available for : Chrome / Firefox

Page Ruler

Most useful and flexible ruler tool to measure the pixel perfect dimension of the elements on the screen. Fast and reliable when compared to the other measuring tools available. Measuring is so simple, just click, drag and get the dimensions.

Available for :  Chrome / Firefox

Note : If you need ruler for Firefox try MeasureIt

Fontface Ninja 

Essential browser plugin to analyze and verify the font face used across the website. The lovely feature is the UI of the extension. You can also feel it by activate the extension and hover the mouse on the required text. A pop-up clearly shows the Font Family, size vertical and horizontal line spacing.

Available for : Chrome / Firefox

Css Viewer

This extension allows you to view the consolidated css property of the element. It’s so easy,  just activate the plugin by right click in the browser window and select the Css Viewer from the right popup menu.  After that hovers the mouse on the element. A new css popup panel appears and lists all the consolidated css attribute and value of the elements. Use”Esc” key to close the popup.  This extension is more helpful in debugging phase.

Available for: Chrome / Firefox

Lorem Ipsum Generator

This is a handy extension to create an appealable dummy text while developing the website. If you are developing a site in WordPress or on any CMS this extension will help you to get the dummy text in a couple of clicks. The best part is it’s an open source project.

Available for: Chrome

If you need extension for Firefox try Dummy Lipsum

Also have a look on Popular Frontend Framework you must try at least once.

Password protection to Website using htaccess

Password protection to Website using .htaccess is much easier than you ever think. This .htaccess authentication is not only for protection. As a developer, we always have multiple staging and dev environment before production. So authenticating those web servers with .htaccess is recommended.  Especially authenticating website with .htaccess will protect your environment from unauthorized access and unwanted SEO crawlings.

password protection htaccess

The site protected with htaccess will prompt for the authentication whenever it gets the hit. 

You can setup this .htaccess authentication within two simple steps.

  • Create encrypted password file.
  • Configure and map the password file in .htaccess

Creating an encrypted password file

First of all, create a new password file in the document root. This password file will hold all username with the respective password in encrypted format. Each encrypted username and password will be in new line. You can create your own encrypted username and password set without relying on any online tools.

$ htpasswd -nbm username Password

Copy the generated encrypted password to the password file.

 “myName:$2y$05$LwGdq19WrsD9w0VzFg0ZuetbL5/bw.S7yyDsjj1rXS13buZuWRBNW”

Note: Give desired random file name to the password file preceded with “.” .

htpasswd command executable is found in the apache/bin if you are using XAMPP in local dev machines. 

 

Configure and map the password file in .htaccess. 

We are almost done, the next thing is to add the below mention lines to your .htaccess file in the document root.

AuthType Basic
AuthName "My Protected Area"
AuthUserFile /absolute/path/to/password/file
Require valid-user

Note:

  • in addition use the full absolute path in the AuthUserFile . If you use relative path it will result in 500 Server error
  • If you use relative path / password file is not accessible  will result in 500 Server error

As a result, you can see an authentication popup whenever you hitting the URL freshly.

htaccess authentication

 

Know furthermore about the encryption options available.

Know furthermore about the htpasswd attributes

Popular Frontend Framework you must try at least once.

Web development reaches new era after the HTML5 and CSS3. The frontend framework is the first thing hits our mind whenever we hearing the word “Let’s develop a new website”. While architecting the project everyone prefer to use the popular front-end frameworks.

frontend-frameworks

This is common that the people like to walk on their legs, Some crazy guys do it by hand, am sure it will be more fun while walking with hands. similarly, I decided to try some of the frontend frameworks which are not that frequently used as Bootstrap and Foundation.

Let’s have some fun!

Here come the heads up for some framework I tried.

Materialize

materialize

Materialize is a modern responsive framework based on the Google’s material design. The materialize frontend framework also support SCSS (CSS preprocessor). It had its own package of icons, button styles, cards etc. The developer who knows less about designing and want to implement the material design then this is the right pick.

Materialize have their own portal for showcasing the websites which are developed using their framework

UIKit

uikit css

UIKit is one of the remarkable frontend frameworks which has the both LESS  & SCSS support. It is considered as highly modular front end framework. The special admiring part of the framework is the naming conviction used for the class.

This framework suits for the developer who have basic knowledge on front end development.

Pure

pure

Pure is a remarkable responsive framework from the popular brand YAHOO! It’s well known for its light weighted CSS modules. Pure doesn’t have JS support library.

Pure is preferred for the developer who wants to develop a responsive site rapidly with lightly weighted frontend framework.

Skeleton

skeleton css

Skeleton is more light weighted when compare to Pure as it only has the basic modules to build a responsive design.  Even though it is lightly weighted skeleton is bare enough to develop a small responsive web application. It also have the responsive grids, and basic components like buttons, forms, table, list etc.

The web development doesn’t require all the styling of the large framework then skeleton is a preferred choice

Numerous frameworks are available now., in which I listed the frameworks that I  tried and admired.

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

Post Feeds to Facebook wall from Web / Mobile Application.

Under this topic, Am sharing that how I implemented a functionality to post feed to users Facebook wall. I used javascript HTTP post method and Facebook Graph API to achieve this.

Am taking a hybrid mobile application was developed using Ionic and AngularJs as an example. That application has the option to share user check-ins, favorites & activity kind of stuff.

Post to facebook wall from mobile applicaiton

Mission

The mission is to post the recent activity of the user to the Facebook wall if share to Facebook option is enabled. The another task is to display posted via “App_Name” and the link to the respective web page in the bottom of the feed.

Mission accomplished

To accomplish the mission of posting the user data to Facebook wall I used the HTTP post method and the Facebook Graph API as I mentioned above.

Code snippets

try {
 $cordovaFacebook.getLoginStatus()
 .then(function(success) {
   // save access_token
   var accessToken = success.authResponse.accessToken;
   var app_id = "Your App ID";
   var content = '&message=YOUR_CUSTOM_MESSAGE&link=YOUR_TARGET_LINK&caption=POST_VIA_NAME&picture=PICTURE_URL';
   var url = "https://graph.facebook.com/me/feed?app_id=" + app_id + "&access_token=" + accessToken + content;
   $http.post(url).then(function(response) {
    // success action
   });
  });
} catch (_error) {
  // Error action
} 

The above example of the application using Ionic & AngularJS

Note: you can use the url variable on any HTTP post or ajax calls

Code Brief

Getting the user login status before posting the feed

on success am getting the user auth token from facebook.

  • app_Id   = facebook developer application ID.
  • YOUR_CUSTOM_MESSAGE : The message to display in the feed
  • YOUR_TARGET_LINK: The URL to navigate if the user click on the Facebook post
  • POST_VIA_NAME : Application / Website name.
    PICTURE_URL: URL of the picture to post along with message

constructing an URL to use with HTTP post method.

Call HTTP post method. Do the success action id the call succeed else it end with “Error action”.

Drop your valuable comments in the Comment box.