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.

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.

Most Common Genesis Hooks and Filters – [WordPress]

I  will list all the most common Genesis hooks and filters used by me while developing a website without boring you with more contents.

For a basic overview of Genesis framework read here.

Genesis hooks filtersWhile customizing a WordPress,  use a child theme to make all your changes so your parent theme will remain clean.

Below mentioned are the common tasks achieved by Genesis hooks and filters while developing a website

  • Change number of columns in Footer.
  • Registering the custom sidebar
  • Hooking registered side bar to appropriate section
  • Change the default position of the primary menu
  • Remove the site title for Frontpage
  • Change the Copyrights content
  • Modify Breadcrumb Prefix and Format
  • Create a new custom post type.
  • Add the custom post to archive query.
  • Remove comments section on Custom post type

Add the following code snippets to the function.php of Genesis child theme.

Change number of columns in Footer

This line will be already there in the function.php. Increase or decrease the footer column count. You can see the respective number of footer sidebars registered in the widget area.

add_theme_support( 'genesis-footer-widgets', 3 );

Registering the custom sidebar

This code snippets let you create and register a custom sidebar which allows you to add the widgets to your website

genesis_register_sidebar( array(
 'id'          => 'Unique_id_for_custom_sidebar',
 'name'        => __( 'Name for Custom sidebar', 'theme_name' ),
 'description' => __( 'Description for custom sidebar', 'theme_name' )
));

Genesis Hooks to pull registered side bar to appropriate section

This Genesis hook method allows you to replace the sidebar content in the place of declared hook section
Refer here for Complete hook Guide.
You can add custom HTML wrapper to the custom sidebar with the help of “before” and “after” parameter.

add_action( 'genesis_header_right', 'menu_header_right');
function menu_header_right() { 
 if (is_active_sidebar( 'menu_header_right' ) ) { 
   genesis_widget_area( 'menu_header_right', array( 
    'before' => '<div class="menu_header_right widget-area"><div class="wrap">',
    'after' => '</div></div>', ) );
 }
}

Change the default position of the primary menu

These Genesis hooks allow you to change the default position of the primary menu by removing it from default position and add it to the appropriate section using the hook name.

here I remove the primary menu from its default position and add it to genesis_header_right

remove_action( 'genesis_after_header','genesis_do_nav' ) ;
add_action( 'genesis_header_right','genesis_do_nav' );

Remove the site title for Frontpage

Remove the title section of the page if it is front page using condition and remove action.

add_action( 'get_header', 'remove_title_frontpage' );
 function remove_title_frontpage() {
  if ( is_front_page()) {
  remove_action( 'genesis_entry_header', 'genesis_do_post_title' );
 }
}

Change the Copyrights content

Here am used a filter to change the content of the existing footer credits function. Replace the echo command content with the appropriate HTML code.

add_filter( 'genesis_footer_creds_text', 'footer_creds_text' );
function footer_creds_text () {
	echo 'Custom HTML Code';
}

Modify Breadcrumb Prefix and Format

Modify the args[‘sep’] value to change the breadcrumb separator. You can also add the prefix to the breadcrumb. Here am adding a single space for better visibility and readability.

add_filter( 'genesis_breadcrumb_args', 'custom_breadcrumb' );
function custom_breadcrumb( $args ) {
  $args['labels']['prefix'] = '';
  $args['sep'] = ' > ';
  return $args;
}

Create a new custom post type

By creating a custom post type you can have a separate post section under WordPress admin menu with given name. The below code snippet will create custom post type “News” and add it to the WordPress admin menu. Change the values from “News” to require name if you want to create your own post type

add_action( 'init', 'create_custom_post_news' );

function create_custom_post_news() {

	$labels = array(
			'name' => __( 'News' ),
			'singular_name' => __( 'News' ),
			'all_items' => __('All News'),
			'add_new' => _x('Add new News', 'News'),
			'add_new_item' => __('Add new News'),
			'edit_item' => __('Edit News'),
			'new_item' => __('New News'),
			'view_item' => __('View News'),
			'search_items' => __('Search in News'),
			'not_found' =>  __('No News found'),
			'not_found_in_trash' => __('No News found in trash'),
			'parent_item_colon' => ''
			);

			$args = array(
			'labels' => $labels,
			'public' => true,
			'has_archive' => true,
			'exclude_from_search' => false,
			'menu_icon' => 'dashicons-admin-post',
	    'rewrite' => array('slug' => 'news'),
	     'taxonomies' => array( 'category', 'post_tag' ),
	      'supports'  => array( 'title', 'editor', 'thumbnail' , 'custom-fields', 'excerpt', 'comments', 'genesis-cpt-archives-settings' )
	 );

		register_post_type( 'news', $args);

}

Add the custom post to archive query

The newly created custom posts are not available in the search result of the website.  Add the newly created post to the archive with the following code.
Add the name given in register_post_type to the $query->set( ‘post_type’, array()) seperated by coma

add_action('pre_get_posts', 'query_post_type');
function query_post_type($query) {
  if($query->is_main_query()
    && ( is_category() || is_tag() )) {
        $query->set( 'post_type', array('post','news') );
  }
}

Remove comments section on Custom post type

Here I removed the comment section for the custom post type news.

add_action( 'init', 'remove_custom_post_comment' );

function remove_custom_post_comment() {
    remove_post_type_support( 'custom_post_name1', 'comments' );
}

These are the most commonly used hooks and filters while developing the normal website. Start developing your WordPress site with Genesis framework.

Genesis Framework Simple Reference Guide

In Genesis Framework Simple Reference Guide, Let’s start with a small intro about Genesis framework. Genesis framework is most flexible WordPress theme with more customization option. Genesis framework let you develop a site on WordPress in a way you want it. If you prefer WordPress for development this framework will give you more power and flexibility to develop the website. You can create your own customized theme using Genesis framework.

Genesis Framework Simple Reference Guide

 

Genesis framework is one-time purchase.

So, it’s worth buying and use it for multiple site development

Genesis Framework Simple Reference Guide

Genesis framework’s customization based on the hooks, filters. Using these options you can develop a website right from the scratch.

Hooks –   Inject the desired code at desired place without changing any WordPress default file.

Filters – allow you to modify/decorate  the existing function

Download and install the Genesis Theme and also install the child theme for Genesis and activate it.

Do all the customization in child themes function.php

This will keep the parent theme clean.

You can put your custom contents section in the required place by creating/registering the sidebar and  hook it in function.php ( child theme)

Refer the below image for the Genesis Hook guide

Genesis Framework Simple Reference Guide

the hook guide will help you to understand the names given to refer section of the website. Use this hook name to replace it with required custom contents.

Registering sidebar in Genesis

If you want to put your custom HTML code or content in place of the hook names, first you need to register the sidebar. The registered sidebar will appear in the Appearance – > Widget section of the WordPress.

Once the register sidebar appears in the widget section drag drop the require widget to the corresponding sidebar. You can also insert custom content blocks to the registered sidebar. These content block let you add custom codes.

genesis_register_sidebar( array(
 'id'          => 'menu_header_right',
 'name'        => __( 'Menu - Header Right', 'custom_name' ),
 'description' => __( 'custom_description.', 'custom_name' ),
) );

Add the above code snippet to the child themes function.php. Now you can see the new sidebar available in widget page with the name mentioned in the code.

Genesis Framework Simple Reference Guide

Hook the registered sidebar

After registering the sidebar,  we need to determine the place where the appropriate sidebar needs to be hooked.

add_action( 'genesis_header_right', 'menu_header_right');

function menu_header_right() {
 if (is_active_sidebar( 'menu_header_right' ) ) {
   genesis_widget_area( 'menu_header_right', array(
  'before' => '<div class="menu_header_right widget-area"><div class="wrap">',
  'after' => '</div></div>',
  ));
 }
}

This piece of code will hook the custom sidebar in the place of  “genesis_header_right”  as mentioned in the hook guide. With the help of  ‘before’ & ‘after’ attribute, you can wrap side bar with a custom HTML & class for styling.

Genesis Filters

Filters in Genesis tends access to modify the result of the existing function. I will explain the filter concept with the example.

In a breadcrumb, the default separator will be “/” and the breadcrumb will look like “Home/some_page” If I want to modify the default separator of the breadcrumb from “/” to “>” which can be achieved by filters.

function change_breadcrumb_separator( $args ) {
   $args['sep'] = ' > ';
   return $args;
}
add_filter( 'genesis_breadcrumb_args', 'change_breadcrumb_separator' );

Genesis general settings

Apart from the custom hooks & filters Genesis framework has some general settings.

  • Default site layout
  • Section for adding logo image
  • Breadcrumb options
  • Comment and Track Backs
  • content archive
  • Blog page template
  • Header / footer scripts.

These titles itself reveal the core purpose of the settings.

Genesis framework simple reference guide gave a basic idea about implementation for more hooks and filters visit the link below.

Most common hooks in genesis framework used for website development are available here.

Ready made themes also available in Genesis framework. Check it out!

Setup Sass In Create-React-App Without Ejecting

If you are using Create-React-App module to manage your no configuration react application development environment, this guide is to setup Sass compiler into the environment without ejecting the setup.

Setup Sass In Create-React-App Without Ejecting

We know create-react-app comes with eject option, which will deploy all automatic confirmation to manual configuration, Even for a professional developers, it will be a headache while doing an upgrade in future. Currently, the create-react-app doesn’t come with Sass compiler but we can integrate it out of the box. This tutorial is to explain how to setup Sass compiler in the existing/new application without ejecting.

Node and NPM needs to be installed before continuing following steps.

Step 1:

Create react app using create-react-app by following syntax

npm install -g create-react-app
create-react-app
my-app cd my-app/
npm start

Step 2:

Install node-sass-chokidar from npm

npm install --save node-sass-chokidar

Step 3:

Open package.json and add the following into scripts configuration.

"scripts": {
“build-css”: “node-sass-chokidar src/ -o src/”,
“watch-css”: “npm run build-css && node-sass-chokidar src/ -o src/ –watch –recursive” }

To watch sass and compile use following command

npm run watch-css


Step 4:
Sometimes we miss to run the command while running the application, So let’s add this watch css to the application run command.

"scripts": {
“build-css”: “node-sass-chokidar src/ -o src/”,
“watch-css”: “npm run build-css && node-sass-chokidar src/ -o src/ –watch –recursive”,

 

“start”: “react-scripts start”,

 

“build”: “react-scripts build”,

 

“start-js”: “react-scripts start”,

 

“start”: “npm-run-all -p watch-css start-js”,

 

“build”: “npm run build-css && react-scripts build”, }

now we don’t need to run separate commands to compile css.
Now running

npm start

and

npm run build

The command builds Sass files too.

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