Thursday, March 26, 2020

Angular Tutorials - Anchor bind tag click event example without href

In this blog post, we are going to learn how to bind the click event to the anchor tag.
Angular Tutorials - Anchor bind tag click event example without href

Anchor bind tag click event example 

In Angular applications, We have anchor tags used for following places

  • navigate to a different page
  • Add/remove HTML elements dynamically

You have to write a code to handle the anchor click event binding. Whenever use clicks on anchor event, It triggers the DOM event binding.
First, create an angular application using ng CLI command.

Anchor click event without href

Anchor tag has href and clicks event in legacy applications, but href are not supported
In HTML template file, please add anchor tag with click event like as follows

important points
  • href  is not required as it forwards the request
  • you can also add href="javascript: void(0);"
  • Add click event with calling function
  • Anchor displays as link, change the style as cursor =pointer to clickable like a button

<div style="text-align:center">
       Angular Button Click Event Example
<a class ='btn' style="cursor:pointer"(click)="clickme();">click me</a>
<a href="javascript: void(0);" (click)="clickme()"> click here

In your typescript code

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

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  constructor() { 


    this.msg='anchor tag is Clicked';
    return this.msg;

navigate to different page using routerLink 

 In applicaitons, you can navigate from one page to other page, This can be achieved using href in legacy jquery apps. In Angular application, same can be achieved with routerLink attribute as seen below
router link path must be configured in router file

  { path: 'home', component: HomeComponent }

Tuesday, March 24, 2020

Difference between ES6 Promise and RXJS Observable in javascript with examples

This blog covers the difference between observable and Promises observable and promises in Javascript with examples.

observable and promises are used to handle the asynchronous calls in a javascript. This will be helpful to consume the rest API calls in front end applications like angular, react and vuejs as well as server-side applications with node environment.
Promises are inbuilt features introduced in ES6 or ES2015 for handling asynchronous operations Observable is a class in the RXJS library which is mainly used to handle multiple asynchronous calls and needs cancellation during operations.

ES6 Promises not cancellable 

 These are mainly used to avoid callback hell. Promises to handle single events and single results. if the operation is successful, means promise resolved, The result is a value else operation throws an error message, promise reject, the result is an error message ES6 Promises are not cancellable. The promise is useful for single async operations which are not cancellable First promises are declared using new Promise, provide the synchronous code inside.
var myproimse = new Promise((resolve, reject) => {
  if (success) {
    resolve("single object is returned");
  else {
    reject("Failure message"));
Once a promise is defined, you need to provide then and catch to catch success and error events.
promise.then((success) => console.log(success))      // single object is returned
       .catch((err) => console.log(error));    // Failure message
callback in then will be executed for promise resolve and catch will be executed for error messages.

 RXJS Observable are cancellable 

This works with multiple events in a stream of data flow These are button click events as an example, This will not be called until user-initiated action. The result is either success, failure and complete are the minimum events, but there are multiple events So we have to provide callbacks for each of these events.
 Here is an example of creating an observable defined with three events next event with value error event with failed message complete event without parameters
import { Observable } from 'rxjs';

const observableObject = new Observable(myobserver => {"successvalue");
observable object is subscribed using subscribe with three callbacks for success,error and complete
console.log('Start ');
  next(value) { console.log('next: ' + value); },
  error(err) { console.error('error: ' + err); },
  complete() { console.log('complete:'); }
and output is
next: successvalue
error: failed

Difference between ES6 Promise and RXJS Observable in javascript

Promise Observable
Asynchronous nature Asynchronous calls
Once asynchronous calls are initiated, not cancellable can cancel the request using unsubscribe() method
Always returns single value - either promise is resolved or rejected error message multiple vallues based on failure,success,retry,cancel operations
works with single event Multiple event streams are supported during time progress
Retry is not possible Retry is possible using retry operator, use retryWhen based on conditional operator
Early loaded and returns the single result either success or failure Lazy loaded and returns multiples values when required
No operators supports Supports array kind of operators -map,filter,forEach,reduce etc..

Saturday, March 21, 2020

Javascript example - How to convert number to decimal number or add zeroes

In this blog, we will discuss several ways to add pad two zeroes to the given number or a string.
For example, We have a number=12, we have to output the number to 12.oo by adding two zeroes to the number In javascript, numeric values are represented in Number type. The number can be 12,-12,12.00. There is no differentiate between integers (12,-12)and floating numbers (12.00) The number can also be store in the form strings("12")
Convert to a decimal using with toFixed(2) method
 Number.toFixed() method used to format the given number, outputs floating-point number. here is syntax

This takes decimalplacescount as input for a given number only, which returns the digits count after decimal point(.)
In the below example The given number is converted to decimal number with 2 digits if the input is string, it throws TypeError:strValue.toFixed is not a function, convert the string to number using parseInt and use toFixed method
let value=12;
console.log(typeof value); //number

console.log(value.toFixed(2)); //12.00

let strValue="34";
console.log(typeof strValue); //string
console.log(strValue.toFixed(2)); //TypeError:strValue.toFixed is not a function

let num=Number.parseInt(strValue)

Convert to decimal using toLocaleString() method 

 toLocaleString() method in Number used to localize version of a given number.
locale is en or ES,
Optional configurations are minimumFractionDigits =2 which is to add number of digits after a decimal point
 It accepts English language
var value = 17;    
var decimalNumber = value.toLocaleString("en",{useGrouping: false,minimumFractionDigits: 2});

Friday, March 20, 2020

javascript example - Add padding/leading zero to a number of astring in typescript

In this blog post, Let's see an example of add pad zeros to the number/strings with below examples

  • add leading zeroes to date month 
  • using padStart() method in ES08
  • pad zero to string in javascript 

 Add leading zero to the month of date object in javascript 

IN blog URL, default post URL is year/month/postname ie 2020/02/my-postname .
Suppose Date object in javascript, getMonth return number as 3 instead of 03. When you are migrating blog to hugo, or other providers URL need to change the month from 3 to 03 as seen below
var date= new Date();
console.log(date); //2020-03-18T15:16:08.699Z

console.log(date.getMonth()+1); //3

Appending zero string to the given number or a string 

add the month object with zero string to makes the beginning of a number

var date= new Date();
console.log(date); //2020-03-18T15:16:08.699Z
let month=date.getMonth()+1
console.log(month); //3

console.log(stringMonth); //03

padStart method ES2017 method

padStart method is a new method introduced to String objects in ES08. Here is a syntax for it
string.padStart(outputstringlength,padding value
Accepted parameters
outputstringlength - output length string
padding value - adding value to start of the string, This is optional, default is empty space Return type - padded the given string with padding value and output is a string of length given.

const strNumber = '9';
console.log(strNumber.padStart(2, '0')); // 09

Wednesday, March 18, 2020

Javascript example - remove leading zero from a string of number

Delete leading zero from a number in javascript 

  Suppose if you have a number or string like 01, 003, the output is 1,3 How do you trim the leading zero from a string?

There are several ways to trim leading zeros from string numbers in javascript.
trim leading zero in javascript

  • Using regular expression in the replace method
  • parseInt() and parseFloat() method

Regular expression with String.replace()method

 provide regular expression with replace () method in string
var strNumber = "0049";
console.log(typeof strNumber); //string

var number  = strNumber.replace(/^0+/, '');

console.log(typeof number); //number
console.log(number); //49
^0 character enables to match the zero at the beginning of the string and replace it with an empty string.

Removing leading zero from string using Number constructor

 if given string contain leading zeros, return number by truncating zero using Number constructor.
var strNumber = "00012";
var number = Number(strNumber);
console.log(number); //12
And another way is using multiply string by 1
var strNumber = "00034";
console.log(typeof strNumber); //string

var number = strNumber*1;
console.log(typeof number); //number
console.log(number); 34
use parseInt() method
if the string contains a number of integers, no floating value
var strNumber = "000324";
console.log(typeof strNumber); //string

var number =parseInt(strNumber)

console.log(typeof number); //number
console.log(number); //324
if given string number is floating value, use parseFloat() method as below
var strNumber = "000124.12";
console.log(typeof strNumber); //string

var number =parseFloat(strNumber)

console.log(typeof number); //number
console.log(number); //124.12

Monday, March 16, 2020

Typescript Example - Ways of Checking null or undefined of an object in - using Typeguard

checking null or undefined of an object in typescript 

 In this blog post, I will take you to the following examples

Typescript Example - Ways of Checking null or undefined of an object in - using Typeguard
  • Undefined or null check with if conditional expression
  • Typeguard null and undefined union check
  • using Optional Chaining and nullish coalescing operators
  • lodash/ramda isNil method 

checking null or undefined of an object in javascript

 In javascript, If the condition is used to check null or undefined values Typescript is a superset of javascript with an extra feature, typing, assertions, Every piece of code works in typescripts.

console.log('Not null')}
the expression must be evaluated to true or false an expression evaluated to false for below values
empty string spaces- ""
NAN - Not number zero
Let's see an example
if ( obj !== 'undefined' && obj !== null ) {
console.log('Object is Not Null');
This works in javascript and typescripts.
Let's see an example of doing the same thing with type guards in typescripts.

Typeguard null and undefined union check Typescript 2.x

 isNullOrUndefined function is defined with accepting object type, null types are added as Union type with type guard syntaxes and return boolean values.

function isNullOrUndefined<T>(object: T | undefined | null): object is T {
  return <T>object !== undefined && <T>object !== null;

let obj=null;

console.log(isNullOrUndefined(obj)); //false
let obj1=123;
console.log(isNullOrUndefined(obj1)); //true

using Optional Chaining and nullish coalescing operators 

Optional Chaining and nullish coalescing operator are introduced in ES11, Typescript also implemented the same in 3.7 version. These both are check for null and undefined values Optional Chaining operator ? is used to checking the account is null or undefined, It will return id if an account is not null or undefined, else return undefined
let account={
let deparmentid=account?.id?
lets an example on nullish coalescing operators

let account=null;
let deparmentId=account??.id
if an account is not null or undefined, returns id, else returns account

JQuery null or undefined

To check in javascript or jquery , use typeof operator.
typeOf checks objects, returns undefined if the object is undefined or null

if(typeof obj == "undefined"){
 console.log('Object is null');

lodash/ramda isNil method 

 lodash and rambda provides isNil method to check for defined or not
return type true/false - true - for Nullish values, else false
Accets object to check for nullish values let's see an example
let obj;