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.

The best programming tricks you need to learn now

Programming is one of the most creative jobs to do. To be a good programmer, learning new tricks and being compatible with the changes in programming field is quite necessary. On daily basis, different rules and modifications are introduced in the field of programming. There is always some programming tricks you need to learn in the field of programming. New challenges always come and go in the field of programming. To be a good programmer all these challenges need to faced with proper dedication and creativity. Read the blog below to know best programming tricks.

The-best-programming-tricks-you-need-to-learn-now

Readability

Comments are an important aspect of the readability. Understanding a code after some period of time becomes quite difficult, however with the use of appropriate comments, you can reuse your code. It guarantees fast debugging and designing of your code. Once people get to know your code, they start to know you as a programmer. It is a mistake that difficulty gives your code a weird look. The reality is that difficult things coded in an easy manner are the best feeling.

You will appreciate easy programs when you identify an error. Readability assists you cross-check code without getting a headache. Everyone experiences errors in their own manner. Readability comes into play when you can present your code in the programming languages.

Express your program code in such a manner that your colleagues can understand it easily. If you have a client project, readability will play a crucial role in customer satisfaction. According to the experts, readability always has an upper hand over the unreadable code.

Client Dealings

In order to become a good programmer, the important thing to grasp is the client’s engagement or interaction. The whole bunch of requirements of clients may be unknown to your team lead or the manager. It is your accountability to provoke requirements from clients as you move ahead in your project. Give a suitable platform for the client to engage with you easily.

Discuss thoroughly that may help them to recall their requirements. There is more than one technique of doing a particular task. Dealing with clients on the continuous basis can guarantee fulfillment of all requirements. Be confident about your work and interact more with your customers. The code written helps the client to get their needs fulfilled.

Grow your Network

Go to seminars and meetings. Interact with other programmers to know the programming tricks, guidelines, and rules. At the least, you will have new colleagues; at the most, you can be in touch with experts who are ready to train you. In learning anything, networking is an important asset for an expert programmer. Try to be active on social media platforms, for instance, LinkedIn is an amazing platform to manage your professional network. Be skilled with the several programming languages in multiple domains. Take part in quiz, competitions and other programming events to boost your programming skills and tricks. Technical brilliance and good design are the features of a great programmer. Ensure you continue them.

Keep learning

Learning is the best programming trick, being a student always is the best thing to learn anything. Life gives you a number of things to learn. Always be active on your personal activities like reading books, playing games and taking part in outings. Always sharpen your skills, reflexives and stay up to date with the changing world. Always try to add something new to your skills. Don’t try to indulge in multiple things at a single time, get updates on new languages and frameworks, and get to know about their basics. Learning ensures you are updating your skills and getting new programming tricks.

Take initiative to learn on new projects on regular basis. Take these projects seriously, always treat them as a challenge and as a chance to further enhance your programming skills into long-term memory. As a programmer adapt quickly to changing requirements. When requirements vary, the tricks to code vary too. Adaptiveness is the important skill to be a good programmer.

Author’s bio:

I am a professional content writer since 2011 working with SEO Services Company Delhi and the graduate of the English with a degree in Mass Communication. My written blogs and articles have been published in several online publications. I am fond of writing, reading, traveling, and Internet surfing.  

 

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.

Essential Frontend Development Tools Used By Developers

There are various factors that influence the development of a complete website or an application. Being a frontend developer, you are required to prioritize your skills and put efforts in the right direction to ensure everything is developed properly. There are scores of frontend development tools that oil the wheels of front-end development. In this article, we have discussed the essential development tools to help you develop your web project on time and within budget.

Essential Frontend Development Tools Used By Developers

Chrome Developer Tools

What about if you could edit CSS and HTML in real-time and analyze the performance of your website thoroughly? Google’s built-in Chrome Developer tool lets you do the same on Chrome and Safari. You can get access to the internals of web application; optimize the loading flows with the help of network tools and can analyze how the browser is performing at present.

Twitter Bootstrap

Looking for an open-source web framework for front-end development of websites and applications? One of the widely used frameworks is Twitter Bootstrap that contains design templates for typography, forms, buttons, navigations and JavaScript extension. It helps developers support application’s new elements in a quick and convenient way, and cut down the amount of code and time to build your project.

Sass

Sass is something the front-end developers cannot afford to neglect. It is the most reliable and robust CSS extension language that helps to expand the functionality of an existing CSS of your suite. It helps writing maintainable and future-proof code while reducing the amount of Cascading Style Sheets (CSS) you have to write. The development tool is compatible with all CSS versions and comes with tons of features that help you meet your goals before the deadline.

Sublime Text

Sublime Text is the widely used code editor that features a well-designed and speedy user interface. The keyboards shortcuts of the program help to perform changes to multiple areas simultaneously. It also supports quick navigation to lines, symbols, and files. It is compatible with many programming and markup languages.

Foundation

Foundation is among the most advanced and responsive CSS and HTML5 frameworks that facilitate the front end development of top-notch websites and applications. It is a flexible and customizable framework that allows designing visually appealing websites, apps, and emails. The features help you prototype and modify to get your projects polished.

Emmet

Being a front-end developer you are in need to have certain tools to help you write HTML, CSS or XML coding without irregularities. The Emmet (formerly Zen Coding) is a set of plugins that help developers write and edit the code of a website in no time. It uses a specific syntax to expand abbreviations of code into complete HTML code. It has been incorporated into several plugins and text editors developed by the Emmet team. However, it is not dependant on any text editor and works directly with text rather than with any particular software.

GitHub

GitHub is another prolific development tool that lets you view the changes you’ve made and undo these changes in case of errors. The repository hosting service offers several other features such as task management, bug tracking and wikis for projects.

Hope you will find these frontend development tools helpful in developing full-fledged websites and apps within a given time frame and budget.

Author Bio:

Angela is serving as senior editor and analyst. She has tremendous expertise in Spying Apps for kids monitoring, employee monitoring, business management, and business security. The series of published articles on global forums are the testimonies that she is expressive and can naturally convince readers through her creative works. Follow her on twitter @LatestTechBlog

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.

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.