Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Angular 7 Project Setup

Posted in Angular

kodecrash

In this section we will go through the steps involved in setting up Angular 7 project. Very recently angular team released version 7 of Angular. You can browse the latest features of Angular here.

To setup latest angular version on your machine you will need Node JS version 8.x or 10.x. You can download Node JS here. Node JS is a JavaScript runtime to build web and mobile applications using JavaScript.

Angular CLI
After installing Node JS you will need to install angular cli. Angular CLI is a command line interface for Angular. Using Angular CLI it becomes very easy to develop, test and build angular applications.

To install angular cli open the npm terminal and use below command.

 npm install –g @angular/cli 

This command will install latest angular 7 version globally on your machine. If you are already using Angular 5 or 6 versions, above command will update your angular cli version to latest version i.e 7. Your existing applications may stop working after upgrading the angular version. So make sure you have latest Node JS version i.e 8.x or 10.x before installing angular.

If you are planning to upgrade existing angular application, please follow the instructions on https://update.angular.io/.

Once the angular cli is installed you are now ready to create angular application from scratch. To check the installed version of angular use below npm command.

  ng --version 

If you get this error ‘ng not recognized as a internal or external command’ try re-installing the angular cli.

Re-installing angular cli

  npm uninstall -g @angular/cli
  npm cache clean
  npm install -g @angular/cli

Use your favorite code editor to build your first angular application. I usually prefer visual studio code. You can download it here.

Create new app
Use npm command below to create new angular project using angular cli.

 ng new myAngularApp

Above command will generate new angular application and download the dependencies for your project. Now it’s time to start your application. Go to the project directory myAngularApp and use below npm command.

 ng serve  

This command will run your application locally using default port number as 4200. You can change the port number with the help of –port 5600 by appending it to the above command.

Build app
To create a production build of your application use ng build command. However, ng build creates a production build of your application in a “/dist” directory of your application folder.

You can now able to start creating your first angular application.

Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Custom Events in JavaScript

Posted in Javascript, javascript interview questions

Custom-events

In JavaScript, there are number of built in events like click, mouseover, submit, scroll etc. There are some drawbacks with these built in browser events. They works only with DOM elements.

Here is an example of click event:

document.addEventListener('click', function(event) {
  
    alert('Button Clicked');
  
});

Above code works with DOM element such as div, button, anchor tag where click event is attached. This is useful when you want a user to perform some action on your web page.
But you can create your custom events in JavaScript. JavaScript provides a way to create and dispatch a custom events as shown below.

var myDialogEvent = new CustomEvent("showDialog", {
    cancelable: true,
    detail: {
          desc: "Display alert message with custom text",
          time: new Date(),
    }
});

Create a CustomEvent object and pass the details about the events. However, detail and cancelable parameters are optional. You can pass empty object to the newly created custom event object.

var myDialogEvent = new CustomEvent("showDialog", {});

cancelable: true means events can be cancelled using event.stopPropagation.
In the detail you can mentioned some description about the event.

Dispatch Event

You can dispatch the event using window.dispatchEvent

 window.dispatchEvent(myDialogEvent);

The ‘myDialogEvent’ gets triggered once you dispatch it. It’s time to create a listener for your custom event. Listening for a custom event you just created is similar to adding a listener for DOM events.

window.addEventListener('showDialog', function(event) {
    if (event.detail) {
        alert(event.detail.desc);
    }
});

Once the event is triggered above code handle the ‘showDialog’ event and display an alert with the event description.

Use custom events if you are creating any JavaScript library or framework for your projects. If you have used any JavaScript framework like React or Angular with JQuery it custom events would be a good choice for communicating any Angular or React component with JQuery code.

Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Arrow functions in JavaScript

Posted in ECMAScript, Javascript

Arrow functions are newly added type of functions in ES6(ECMAScript 6). They are just a compressed way of writing normal functions.

Arrow functions are also called as ‘Fat Arrow functions’.

function add(x, y) {
  return (x+y);
}

var result = add(6,5); // will output 11

This is the normal JavaScript function. Let’s see how above code is written using arrow functions.

var add = (x, y) => {
    return x+y;
};

var result = add(6,5); // will output 11

Look at the above code “function” keyword is replaced by fat arrow. Here is another shortest form of arrow function if we have one line of code inside function body, we can skip those curly braces and ‘return’ keyword while returning values from the function.

  var add = (x, y) => x+y;

If we have multiple lines inside function body then use of curly brace is mandatory. Let’s try using arrow functions in constructor functions.

function Car() {
    this.name = 'BMW';
    this.speed = 50;

    this.increaseSpeed= function() {
       this.speed+= 10;
    }
}

Now, create an object for the Car function.

var mycar= new Car();

mycar.increaseSpeed(); 
console.log(mycar.speed); // will output 60

But consider a case where we want to increase the car speed after 5 seconds. We will use setTimeout function here.

function Car() {
    this.name = 'BMW';
    this.speed = 50;

    this.increaseSpeed= function() {
      setTimeout(function() {
         this.speed+= 10;
      }, 3000);  
    }
}

var mycar= new Car();
mycar.increaseSpeed(); 
console.log(mycar.speed); // will output 50

In this case, after calling increaseSpeed function will not increase the car speed because we are calling a member variable ‘speed’ inside setTimeout function and this setTimeout function has it’s own scope. So the constructor function car’s scope is lost and ‘this’ variable inside setTimeout function has no longer access to the car constructor.

In order to access member variables using ‘this’ keyword inside setTimeout scope use fat arrow functions.


Look at the Car constructor function using arrow function.

function Car() {
    this.name = 'BMW';
    this.speed = 50;

    this.increaseSpeed= function() {
      setTimeout(() => {
         this.speed+= 10;
      }, 3000);
    }
}

var mycar= new Car();
mycar.increaseSpeed(); 
console.log(mycar.speed); // will output 60

We have replaced the setTimeout function syntax to fat arrow function. Fat arrow syntax preserve ‘this’ context. So no need to save the context in any temporary variable like that or self and use that temporary variable inside setTimeout function.

To summarize shorter syntax and flexibility of this keyword context these are the main advantage of using arrow functions

Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Creating a simple grunt task

Posted in Javascript

Grunt is a JavaScript task runner used to automate the common tasks such as JS/CSS file minimization, concatenation of multiple JS/CSS files, Sass compilation, JS linting, code formatting etc.

To get started with grunt you need to install node JS latest version from node JS website.

https://nodejs.org/

Create Node project

From node.js command prompt, go to the project directory.
grunt-1

Type: “npm init”, then: “enter”
grunt-2
follow steps, enter only a name for the site, no need to change other default values. “npm init” command creates a package.json file. Refer the screenshot below.
grunt-3

Install grunt
Use the npm command below to install grunt specific to your project.
grunt-4
–save-dev command adds the dev dependency in the package.json file.
package.json file will look like this.
grunt-5

Create Gruntfile.js in the project root directory. We will use this file to create and configure grunt tasks. Add the below code in the Gruntfile.js.
grunt-12

It’s time to create a grunt task. Create a simple grunt task named logTask using grunt.registerTask function.

  grunt.registerTask('logTask', function() {
    console.log('Inside Log Task');
  });

Your gruntfile will look like this.
grunt-6

Now call the logTask using the command below. “Inside Log Task” text will get printed in the console.

     grunt  logTask

grunt-7

You can create multiple grunt task in the same Gruntfile.
grunt-8

To call the formatTask use the command below.

    grunt formatTask

grunt-9

You can run the above tasks simultaneously by calling both task into the new task.
grunt-10

grunt-11

Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Custom Filter in Angular JS

Posted in Angular JS

To register a filter you need to call the function angular.module().filter(). The first argument is the name of the filter. The second argument is the filter
factory function. If your filter has dependencies, you can list those as arguments in this function.

Syntax:

custom-filter-angularjs

The factory function returns an anonymous function i.e function with no name or so called as self executing function. This anonymous function accepts one argument which is input to the filter. Second argument is optional it depends on filter functionality. If you want to filter objects from an array then the second parameter can be an array.

Example:

The example metioned below is for a custom filter which reverse the input string.

   var myApp = angular.module("myApp", []);
   myApp.filter("reverse", function() {
    return function(input) {
        if (input !== undefined) {
            return split("").reverse().join("");
        }
    };
   });

   <div>{{ firstname | reverse  }}</div>

The above filter first checks for the input is undefined or not otherwise the filter throws an error on page load. It returns an revers of firstname using reverse and join javascript functions.