Multilingual web app in angular 4

  1. Install Via npm npm install @ngx-translate/core —save and nom install @ngx-translate/ http-loader —save
  2. Import HttpModule, Http, TranslateModule, TranslateLoader and TranslateHttpLoader in module.ts

import { TranslateHttpLoader } from’@ngx-translate/http-loader’;

import { HttpModule, Http } from’@angular/http’;

import { TranslateLoader, TranslateModule } from’@ngx-translate/core’;

exportfunctionHttpLoaderFactory(http: Http) {




declarations: [



imports: [




loader: {



deps: [Http]




providers: [MdDatepickerIntl],

bootstrap: [AppComponent]


3.Create a constructor and translation function in app.component.ts

import { TranslateService } from’@ngx-translate/core’;

import { Component } from’@angular/core’;




styleUrls: [‘./app.component.css’]


exportclassAppComponent {

dir: string;

constructor(privatetranslate: TranslateService) {

translate.addLangs([‘en’, ‘ar’]);




changeLang(lang: string, direction: string ) {

this.dir = direction;




5. add translate button in app.component.html

<buttonclass=”btn btn-sm btn-danger btn-srch pull-right” (click)=”changeLang(‘en’, ‘ltr’)”>En</button>

<buttonclass=”btn btn-sm btn-danger btn-srch pull-right” (click)=”changeLang(‘ar’, ‘rtl’)”>عربى</button>

6.create i18n folder inside assets and create ar.json for arabic language and en.json for english language

code in ar.json


“search”: “بحث”,

“search-for-hotel”: “البحثعنفندق”


code in en.json


“search”: “Search”,

“search-for-hotel”: “Search for Hotel”


Adding sidebar in angular 4

Step 1.   Create new project named angular-sidenav using cli. (ng new angular-sidenav).

Step 2.   Install Bootstrap.

Step 3.   Install angular material ( nom install —save @angular/material)

Step 4.   Install animations (npm install —save @angular/animations)

Step 5.  Open app.module.ts file and import BrowserAnimationModule.

import { BrowserAnimationsModule } from ‘@angular/platform-browser/animations’;

import { BrowserModule } from’@angular/platform-browser’;

import { NgModule } from’@angular/core’;

import { AppComponent } from’./app.component’;


declarations: [



imports: [

BrowserModule, BrowserAnimationsModule


providers: [],

bootstrap: [AppComponent]


exportclassAppModule { }

step 6. Import Component Modules in app.module.ts file From angular material

import { BrowserAnimationsModule } from’@angular/platform-browser/animations’;

import {MdInputModule, MdButtonModule, MdCheckboxModule, MdSidenavModule} from ‘@angular/material’;

import { BrowserModule } from’@angular/platform-browser’;

import { NgModule } from’@angular/core’;

import { AppComponent } from’./app.component’;


declarations: [



imports: [

BrowserModule, BrowserAnimationsModule,

MdInputModule, MdButtonModule, MdCheckboxModule, MdSidenavModule


providers: [],

bootstrap: [AppComponent]


exportclassAppModule { }

Step7.  Include a theme ( Open .angular-cli.json file and add ../node_modules/@angular/material/prebuilt-themes/indigo-pink.css inside styles key)

“styles”: [




Step 8. Add hammerjs for some component like (md-slide-toggle, md-slider, mdTooltip). To install via npm, use the  nom install —save hammerjs command. After installing the package import this into app.module.ts file.

import { BrowserAnimationsModule } from’@angular/platform-browser/animations’;

import {MdInputModule, MdButtonModule, MdCheckboxModule, MdSidenavModule} from’@angular/material’;

import { BrowserModule } from’@angular/platform-browser’;

import { NgModule } from’@angular/core’;

import { AppComponent } from’./app.component’;

import ‘hammerjs’;

Step 9. Add  Material Icons

Add following link in your index.html page. For the more detail  visit Material Design Icons .

<!doctype html>






<metaname=”viewport”content=”width=device-width, initial-scale=1″>


<link href=”” rel=”stylesheet”>






Step 10. Open the app.component.html file and add this code.


<divclass=”row header-row”>

<buttontype=”button”class=”btn btn toggle-menu-button” (click)=”sidenav.toggle()”>

<spanclass=”glyphicon glyphicon-th-list toggle-menu-icon”></span>





<md-sidenav #sidenavclass=”sidebar-nav”>

Menu list here



And add this css code in app.component.css

.header-row {

height: 50px;

background: #0AA713;


.toggle-menu-icon {

font-size: 22pt;

color: #fff;

line-height: 33px;


.toggle-menu-button {

background: transparent;


.sidebar-nav-container {

width: 100%;

min-height: 300px;

height: auto;


.sidebar-nav {

background: #06C604;

width: 300px;


Output of this code is

Adding font awesome icons in angular 4

Install the font-awesome library using nom command line (npm install —save font-awesome).

After completing the installation open .angular-cli.json file and add the font-awesome style.

“styles”: [







Angular 4 getting started | Angular 4 tutorials

Download and install Latest Version Of Node JS from

After completing the Node JS installation open command line Interface(CLI) in windows or Terminal in Mac

Then run npm install -g @angular/cli command for windows or sudo npm install -g @angular/cli command for MAC OS. This command install angular command line interface globally inboxed your machine. If you want to install angular cli with version run npm install -g @angular/cli version command for windows or sudo npm install -g @angular/cli version command for MAC OS. It will take several minutes to complete installation.

For creating a new angular project type ng new my-first-app command. Where ng is angular command come from angular cli and my-first-app is a project name. you can write your own project name instead of my-first-app.

Go to your created folder in my my project folder name is my-first-app so i will type cd my-first-app command to go inside a project folder. You can type your own project name instead of my-first-app.

Type ng serve command in terminal and type http://localhost:4200/ in our browser to view out put of project.

  • We use Visual studio code IDE for coding. Download visual studio code from .

        Adding bootstrap in angular 2

    • Open integrated terminal of visual studio code editor( click view—-> integrated terminal)
    • then type a command npm install —save bootstrap.
    • open .angular-cli.json file from root folder and add the highlighted code line.

Angular 2 Step By Step Tutorials | Angular 4 tutorials

Unit 1. Overview

Angular 2 is an open source JavaScript framework to build web and mobile application in HTML, JavaScript or a language like Typescript that compiles to JavaScript’s. The framework consists of several libraries some of them core and some optional.

  • Why to use angular 2?
  • You can update the large datasets with minimal memory overhead
  • It will speedup the initial load through server side rendering.
  • It is used to build single page application. In single page app everything happens on one page although the URL might change are shown to the user without going to the server.

1.2 Features

  • It is a cross platform framework
  • Angular 2 mainly focused on mobile apps

1.3 Advantages

  • It uses server side rendering for fast views on mobile.
  • It use dependency injection to maintain the application without writing too long code
  • Everything will be component based approach.

1.4 Typescript

Typescript is a free and open source programming language developed and maintained by Microsoft. It is a strict superset of JavaScript, and adds option static typing and class based object-oriented programming to the language. Typescript is used to develop JavaScript applications for the client side or server side execution.

Typescript is designed for development of large applications and trans compiled to JavaScript.

1.5 Architecture:

  • Module
  • Component
  • Template
  • Metadata
  • Data binding
  • Service
  • Directive
  • Dependency Injection

angular2 architucture

1.5.1 Module:

Modules is a block of code which can be used  to perform a single task. You can export the value of something from the code such as a  class. Example for export component class from module as shown below.


The export statement specifies that it is a module and it’sAppComponent class is defined as public and can be accessible to other modules of the application.

1.5.2 Component:

Component encapsulates the template data and the behaviors . The component is a controller class with a template which mainly deals with a view of the application and logic on the page. It is a bit of code can be used throughout an application. The component knows how to render itself and configure dependency injection.

The component contains tow important things one is view and another one is some logic. Every angular2 application have at least one component which is called root component. In real world applications contains large number of components.

For example you can build the application to inform about courses  your application split into 3 components.


The course component have other subcomponent


The benefit of this is it will help us to break a large application with various complex components into small simple components and we can re-use this component in other parts of an application. The component is a plane type-Script class

Like other programming language it will have properties and methods.


Component Are binding with dome.Some time our Component need to talk API to get or send the data in server.


Template tells angular how to display the component. For example:



Metadata tells angular how a class should be processed on the screen and is a way of processing the class. Consider we have a one component called AuthorsComponent which will be a class until we tell angular that it’s a component. You can use metadata to the class to tell angular that AuthorsComponent is a component. The metadata can be attached to Type-Script by using the decorator.


The @Component is a decorator which uses configuration object to create the component &it’s view. The selector creates an instance of the component where it finds <authors> tag in parent html. The template tells Angular how to display the component. The directive decorator is used to represent the array of components or directives.

Data Binding:

Data binding is a process of coordinating application data values by declaring bindings between sources and target HTML element. It combines the template parts with components parts and template HTML is bound with markup to connect both sides. There are 4 types of data bindings:

  • Interpolation: It displays the component value with in the div tags.
  • Property binding: It passes the property from the parent to property of the child. Uses {{ propertyname }} for property bindings.
  • Event binding: It fires when you click on the components method name.uses (event) for event bindings.
  • Two-way binding: This binds property and event by using the ngmodel directive in a single notation.


Services are JavaScript functions that are responsible for doing a specific task only. Angular services are injected using dependency injection mechanism.  Service includes the value, function or feature which is required by the application. Generally service is a class which can perform something specific such as logging service, data service, message service, the configuration of application etc. Services also get the configuration of data from server. Service contains only logic that not related to view.


The directive is a class which contains metadata which will attached to the class by the @Directive decorator. Angular2 has three types of directive

  1. Component Directive
  2. Structural directive
  3. Attribute directive: Attribute directive change the behavior of DOM attribute directive are ngclass and ng style

How to Handle JSON data in Angularjs

To work with JSON data in AngularJs , first of all we need to know about $http request 


$http is an AngularJS service for reading data from remote servers.
The AngularJS $http service makes a request to the server, and returns a response.




 $http.get(' ')
     . success(function( ) {
     . error(function( ) {

The $http service supports the HTTP verbs get, head, post, put, delete.


Lets Make json file jsonData2.json

how to handle json data in angularjs

Now just call this json file in controller by $http service.

how to handle json data in angularjs

Now we are at view and we need to diplay this json data in our page.
how to handle json data in angularjs

Use Localstorage for ionic with ngStorage

Local storage is supported by almost all of browsers these days, that makes it very easy to integrate local storage into the Ionic app. As usual, we can access it this way:
Practically, to add, update or remove an item, we do this:
window.localStorage.setItem( ‘awesome-key’, ‘awesome-value’ );
window.localStorage.getItem( ‘awesome-key’ );
That’s good enough for simple data structure. When data structure gets more complicated, I mean JSON, then it’s gonna be something like this:

var appData = {
name: ‘Awesome App’,
version: ‘1.0.0’,
description: ‘My first awesome app’

/* LATER ON */
// save it
window.localStorage.setItem( ‘app-name’, JSON.stringify(appData));
// retrieve it
var appData = JSON.parse( window.localStorage.getItem( ‘app-name’ ));

Basically, it is fine, but keep dealing with JSON.stringify() and JSON.parse() is very very very annoying and inconvenient.
Luckily, there has an Angular module that helps dealing with this, ngStorage. Since Ionic is based on Angular, we can use it in the application freely. Let’s use it to create a very simple Ionic application, a simple anything app.
Create a new blank Ionic project.

$ ionic start AnythingApp blank

Check whether project is working properly.

$ cd AnythingApp
$ ionic serve

View in browser to see whether it works fine or not. It is a good habit to always verify a good-working initialized project to start with. If any error occurs at this step, you might wanna to re-create project again.
Next step is to install ngStorage as I mentioned above.

$ bower install ngstorage

According to the pre-configuration in .bowerrc, the library is installed at www/lib directory. Okay, we need to include this library into the app, by adding a line in the main www/index.html file.

<! — ionic/angularjs js →<! — add more libraries →<! — cordova script (this will be a 404 during development) →

Add you notice, I add the library right after adding the ionic.bundle.js library, that is the appropriate place to add more libraries into Ionic project.
To use the service, as mentioned in the ngStorage usage guide, we need to inject ngStorage module and the appropriate service when we need.
Next, let’s draft the basic UI for the main view:

Anything App




Okay, the template also does mention the method to add new thing model to the app, and display it on the list below. We will work on this.
To separate concerns on controller, we will create a factory to handle add, remove data from local storage, where ngStorage module is in use.
Inject to main module at first hand,

// Inject ngStorage
angular.module(‘starter’, [‘ionic’, ‘ngStorage’])
and then create the factory,
// create a new factory
.factory (‘StorageService’, function ($localStorage) {
var _getAll = function () {
return $localStorage.things;
var _add = function (thing) {
var _remove = function (thing) {
$localStorage.things.splice($localStorage.things.indexOf(thing), 1);
return {
getAll: _getAll,
add: _add,
remove: _remove

You might wonder, what that $localStorage.things is about. Yay, that’s the cool thing ngStorage provides, we can use the Javascript dot-notation to access the object, which helps us to avoid writing the basic getItem, setItem.
Since, we keep every entry in local storage, we use a single key to keep them as an array. Hence, push() is applied for $localStorage.things.
Following step is to create the controller, which is MainCtrl as we specified earlier in the view.
// controller

.controller( ‘MainCtrl’, function ($scope, StorageService) {
$scope.things = StorageService.getAll();
$scope.add = function (newThing) {
$scope.remove = function (thing) {

Almost done, you can try on browser and see what happens when you try to add a new entry, you’ll get an error…

TypeError: Cannot read property ‘push’ of undefined
at Object._add [as add] (http://localhost:8100/js/app.js:16:25)
at Scope.$scope.add (http://localhost:8100/js/app.js:35:20)
at fn (eval at (http://localhost:8100/lib/ionic/js/ionic.bundle.js:21972:15), :4:279)
at http://localhost:8100/lib/ionic/js/ionic.bundle.js:57514:9
at Scope.$eval (http://localhost:8100/lib/ionic/js/ionic.bundle.js:24673:28)
at Scope.$apply (http://localhost:8100/lib/ionic/js/ionic.bundle.js:24772:23)
at HTMLButtonElement. (http://localhost:8100/lib/ionic/js/ionic.bundle.js:57513:13)
at HTMLButtonElement.eventHandler (http://localhost:8100/lib/ionic/js/ionic.bundle.js:12098:21)
at triggerMouseEvent (http://localhost:8100/lib/ionic/js/ionic.bundle.js:2865:7)
at tapClick (http://localhost:8100/lib/ionic/js/ionic.bundle.js:2854:3)

It happens because we didn’t initialize the key to be used and be watched by $localStorage. Fixing it by initializing the default value for the keys we want to use in the app. Add the following line at beginning of the factory,

$localStorage = $localStorage.$default({
things: []

That’s it for the use of ngStorage. Actually, there are more methods provided by ngStorage, but I guess you will find it very interesting when discovering something useful about ngStorage. Be sure to follow the guide in the ngStorage usage section.
The full source code for this demo:
Check out if you need a reference or have any trouble.

Why Hybrid Mobile Apps Development

When developing an app you have three choices:

1. Native mobile app
2. Mobile web app
3. Hybrid mobile app

From a business viewpoint, one of the reasons to consider a hybrid mobile app is you don’t have to develop a full app for every mobile platform. Since, Web browser or the UI Web View is not identical to the all browser. A hybrid app is cross-platform by design and it solves some of the issues that some experience with full web apps.

A hybrid app is a web app built using HTML5 and JavaScript, wrapped in a native container which loads most of the information on the page as the user navigates through the application. Hybrid apps make us possible to embed HTML5 apps that combining the both best and worst elements of native and HTML5 apps. Hybrid apps provide the best of both worlds i.e. Native and HTML worlds.

How To Make Side Menus In Ionic

There is two side menus in ionic, one is left side menu and another one is right side menu. We can design our side menus as our wish.

For Left Side Menu


<ion-side-menu side=”Left” width=”myWidthvalue+20 is-enabled=”shouldLeftsideMenuBeEnabled”




Your menu content goes Here




UI-Router To Navigate In Ionic Framework


In this post we will learn how UI router to navigate in ionic framework. Ionic comes with the Angular UI router with it, thus we can directly use $stateProvider and $urlRouterProvider to create routes. We need to inject $stateProvider and $urlRouterProvider in our config method to make use of the Angular UI router.

We are going to build a simple two-page view, and a navigation button to navigate between the views. This is a simple example to understand syntax and setup of the router. Lets open www/js/app.js, and then just start coding by using config method like below :

.config (function ($stateProvider , $urlRouterProvider){
.state('' , {



Or follow this picture:
UI-Router To Navigate In Ionic Framework

As you can see, $stateProvider and $urlRouterProvider are injected as dependencies to the config method.

.state('page1', {
url: "/page1",
templateUrl: 'templates/page1.html'

.state(‘page2’, {
url: “/page2”,
templateUrl: ‘templates/page2.html’

Or follow this picture:

angularjs routing

The state method of $stateProvider are used to declare the routes. The first argument of the state method is the name of the state whereas second argument contains route configuration. Route configuration has URL and Template.

url : The URL route that can be accessed via href properties

templateUrl : The path to the view template HTML file

Next we have $urlRouterProvider which provide the default URL as shown below.


See Full code :

.config (function ($stateProvider , $urlRouterProvider){
.state('page1', {
url: "/page1",
templateUrl: 'templates/page1.html'

.state('page2', {
url: "/page2",
templateUrl: 'templates/page2.html'



Or follow this picture:

angular ui router

Our index.html will look like below, where we are adding a back button which will be displayed when we go in any other view than the default view. We also have to tell the router which portion of the page should be updated with the contents of the state, this is done by adding <ion-nav-view>.

follow this picture:

ui router

The contents of page1.html are :

angularjs routing

The contents of page2.html are :

UI-Router To Navigate In Ionic Framework

Hope, it was very helpful for you.

How to use Cordova sqlite plugin in ionic

In this short tutorial , I am going to write how to use cordova sqlite plugin in ionic framework.

Before starting, its better to explain what elements are needed for successful implementation of cordova sqlite plugin. So , let’s start by creating fresh ionic project.

If you are new to ionic and dont know how to install it then read the this post


Start Git bas or NodeJs Command promt and type the following code

  • $ ionic start myApp blank

After download finished, type

  • cd myApp

Now its time to install cordova sqlite plugin . For this run the following code into cli or Command prompt.

  • cordova plugin add

After this , install ngCordova from bower by following command.

  • bower install ngCordova

let’s Start with our ionic project

Now open the app folder into your favourite text editor, mine is sublime text.

Open the www folder there you can  find four subfolders and index.html file.

Open the index.html file into text editor and you can see the code like

  • <!DOCTYPE html>
  • <html>
  •   <head>
  •     <meta charset=”utf-8″>
  •     <meta name=”viewport” content=”initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width”>
  •     <title></title>
  •     <link href=”lib/ionic/css/ionic.css” rel=”stylesheet”>
  •     <link href=”css/style.css” rel=”stylesheet”>
  •     <link rel=”stylesheet” href=”css/ionicons.css”>
  •     <!– IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
  •     <link href=”css/” rel=”stylesheet”>
  •     –>
  •     <!– ionic/angularjs js –>
  •     <script src=”lib/ionic/js/ionic.bundle.js”></script>
  •     <!– cordova script (this will be a 404 during development) –>
  •     <script src=”cordova.js”></script>
  •     <!– your app’s js –>
  •     <script src=”js/app.js”></script>
  •     <script src=”js/controllers.js”></script>
  •   </head>
  •   <body ng-app=”starter”>
  •     <ion-nav-view></ion-nav-view>
  •   </body>
  • </html>

You have to link the ng-Cordova.min.js above the <script src=”cordova.js”></script>  file from lib/ngCordova/dist/ng-Cordova.min.js

And the final index.html looks like

  • <!– ionic/angularjs js –>
  •     <script src=”lib/ionic/js/ionic.bundle.js”></script>
  •     <!– cordova script (this will be a 404 during development) –>
  •     <script src=”js/ng-Cordova.min.js”></script>
  •     <script src=”cordova.js”></script>
  •     <!– your app’s js –>
  •     <script src=”js/app.js”></script>

Now, open the app.js  from js subfolder of www folder. And replace  with following code.

  1. var db=null;
  2. angular.module(‘starter’, [‘ionic’,’ngCordova’])
  3. .run(function($ionicPlatform,$cordovaSQLite) {
  4.   $ionicPlatform.ready(function() {
  5.     if(window.cordova && window.cordova.plugins.Keyboard) {
  6.       // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
  7.       // for form inputs)
  8.       cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
  9.       // Don’t remove this line unless you know what you are doing. It stops the viewport
  10.       // from snapping when text inputs are focused. Ionic handles this internally for
  11.       // a much nicer keyboard experience.
  12.       cordova.plugins.Keyboard.disableScroll(true);
  13.     }
  14.     if(window.StatusBar) {
  15.       StatusBar.styleDefault();
  16.     }
  17.        //db = $cordovaSQLite.openDB({ name: “my.db” });
  18.        db= window.openDatabase(“sql.db”,”1″,”example of sqlite”,”2000″);
  19.       // for opening a background db:
  20.       // db = $cordovaSQLite.openDB({ name: “my.db”, bgType: 1 });
  21.       $cordovaSQLite.execute(db,”CREATE TABLE IF NOT EXISTS people (id integer primary key, firstname text, lastname text,address text)”);
  22.   });
  23. })
  24. .controller(‘dataCtrl’, function($scope,$cordovaSQLite){
  25.   $scope.add= function(user){
  26.     console.log(user.firstname);
  27.     var query=”INSERT INTO people(firstname,lastname,address) VALUES (?,?,?)”;
  28.     $cordovaSQLite.execute(db,query,[user.firstname,user.lastname,user.address]).then(function(res){
  29.       $scope.load();
  30.     });
  31.   }
  32.   $scope.load=function(){
  33.     $scope.alldata=[];
  34.      $cordovaSQLite.execute(db,”SELECT * FROM people”,[]).then(function(result){
  35.       if(result.rows.length>0){
  36.         for(var i=0; i<result.rows.length;i++){
  37.         $scope.alldata.push(result.rows.item(i));
  38.         }
  39.          $scope.$apply();
  40.       }else{
  41.           console.log(“No data Found”);
  42.         }
  43.     },function(err){
  44.       console.log(“error”+err);
  45.     });
  46.   }
  47. });

To insert and populate data from controller,  insert following code between <ion-content></ion-content> of index.html. You should apply ng-controller to your app .

  • <div class=”list”>
  •         <label class=”item item-input”>
  •           <input type=”text” placeholder=”First Name” ng-model=”user.firstname”>
  •         </label>
  •         <label class=”item item-input”>
  •           <input type=”text” placeholder=”Last Name” ng-model=”user.lastname”>
  •         </label>
  •         <label class=”item item-input”>
  •           <input type=”text” placeholder=”Address” ng-model=”user.address”>
  •         </label>
  •         <button class=”button button-positive button-block” ng-click=”add(user)”>Add People</button>
  •       </div>
  •       <div class=”list”>
  •           <div class=”item” ng-repeat=”item in alldata”>
  •            {{}}     {{item.firstname}}
  •           </div>
  •       </div>

If you get any error in running this code, feel free to comment.

Copyright © 2016 InfoxIT Portal. All rights reserved.
Seo wordpress plugin by
Scroll To Top
Visit Us On FacebookVisit Us On Google PlusVisit Us On YoutubeCheck Our Feed