Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Saturday, 11 April 2020

Fix for ng serve --watch is not watching for code changes in Ubuntu

I was running the Angular 8 application on Ubuntu LTS 18.04 on my machine and was having an issue to refresh on code update using  --watch.

Trying to use ng serve and ng build --watch was not watching for code changes and I thought it was something to do with node or angular-cli.
However, I found the solution on Github (https://github.com/angular/angular-cli/issues/8313)
I ran the following on Terminal and apparently, it worked and watching code changes:
echo fs.inotify.max_user_watches=524288 | sudo tee /etc/sysctl.d/40-max-user-watches.conf && sudo sysctl --system

Hope this helps!

Tuesday, 29 October 2019

Angular 7 & Jest & Babel Integration over Jasmine/Karma - AngularSnapshotSerializer.js in the snapshotSerializers option was not found

Steps to integrate of Jest & Babel with Angular 7+:

1. Run the following commands to install:
    # Remove Jesmin/Karma
    npm remove karma karma-chrome-launcher karma-coverage-istanbul-reporter karma-jasmine karma-jasmine-html-reporter
    
    npm uninstall jasmine @types/jasmine
    
    rm ./karma.conf.js ./src/test.ts

    # Install jest    
    npm install --save jest@24.9 @angular-builders/jest@7 @types/jest@24 jest-preset-angular@8 

    # Install babel
    npm install --save-dev babel-jest babel-polyfill
    npm install --save @babel/core @babel/preset-env @babel/preset-flow @babel/preset-typescript    
 

2. On `package.json`, added the following code:
    "scripts": {
      ...
      ...
      "test": "ng test",
      "test:watch": "jest --watch",
      ...
      ...
    }
    ...
    ...   
    "jest": {
      "preset": "jest-preset-angular",
      "setupFilesAfterEnv": [
        "/setupJest.ts"
      ]
    }
 

3. Also, updated the following on the `angular.json`:
    ...
    ... 
    "test": {
       "builder": "@angular-devkit/build-angular:karma",
    ...
    ...
 

Replace with:
    ...
    ... 
    "test": {
       "builder": "@angular-builders/jest:run",
    ...
    ...
 

4. Create the `/setupJest.ts` with below content:
    import 'jest-preset-angular';   
 

5. Create the `/babel.config.js` with below content:
    module.exports = function(api) {

        const presets = [
            '@babel/preset-typescript',
             [
                "@babel/preset-env", {
                    "targets": {
                        "node": "current"
                    }
                }
            ],
            '@babel/preset-flow'
        ];

        return {
            presets,
        };
    };
 


6. And, finally tried running the `ng-test` from a terminal, however, I was stuck with the following error (see picture below):
7. Eventually, managed to fix the issue by adding the file `/src/jest.config.js` with below content:
    module.exports = {
        "transform": {
            "^.+\\.(ts|js|html)$": "ts-jest",
            "^.+\\.[t|j]sx?$": "babel-jest"
        },
        moduleFileExtensions: ['ts', 'html', 'js', 'json'],
        moduleNameMapper: {
            '^src/(.*)$': '/src/$1',
            '^app/(.*)$': '/src/app/$1',
            '^assets/(.*)$': '/src/assets/$1',
            '^environments/(.*)$': '/src/environments/$1',
        },
        transformIgnorePatterns: ['node_modules/(?!@ngrx)'],
        snapshotSerializers: [
            'jest-preset-angular/build/AngularSnapshotSerializer.js',
            'jest-preset-angular/build/HTMLCommentSerializer.js',
        ],
    };
Thereafter, ran `ng test` again and can see the test running thru. I hope it helps!

Friday, 11 October 2019

Construct the dynamic table with specified number of columns on each row as per the size of the data in Angular

The below code is to generate a table with multiple rows with the specified number of columns on each row as per the size of the data array.

Then, on the output, we would be able to generate a table with multiple rows with a specified number of columns.

Friday, 25 May 2018

Angular production test locally with hostName, Port and SSL on

ng serve --prod --build-optimizer --ssl --host demo.yourdomain.local --port 4202

Friday, 16 February 2018

Add sticky content with jQuery

Steps:

1. Add the following on your css file.
.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 5;
}

2. Add the following on your JS file where you need to display the sticky when scrolling up.
jQuery(window).scroll(function(){
    if (jQuery(window).scrollTop() >= 200) {
        jQuery('.classNameOfStickyContentHere').addClass('fixed-header');
    }
    else {
        jQuery('.classNameOfStickyContentHere').removeClass('fixed-header');
    }
});

3. HTML Content
Display me as sticky when scrolling up....

Friday, 6 October 2017

Regular expression to filter the float value with minimum maximum length before and after the decimal

The below javascript example shows whether the given input has float value with limited length numbers before (min 2 to max 5) and after (2) the decimal point .

The Regix is : /^([0-9]{2,5}\.?[0-9]{2})$/
 
function isFloat(input)
{
  var regxExp = /^([0-9]{2,5}\.?[0-9]{2})$/
 var result = input.search(regxExp);
  console.log('Is '+ input + ' valid float number: ', result);
  
  return (result < -1) ? true : false;
}

var input = '312g37.78';
var result = isFloat(input);
console.log('Is '+ input + ' valid float number: ', result);

// Output (FALSE due to invalid letter)
Is "312s37.78" valid float number:  false

var input = '312327.782';
var result = isFloat(input);
console.log('Is '+ input + ' valid float number: ', result);

// Output: (FALSE due to invalid length)
Is "312327.782" valid float number:  false

var input = '3.78';
var result = isFloat(input);
console.log('Is "'+ input + '" valid float number: ', result);
// Output: (FALSE due to invalid length which is less than two (before the decimal point))
Is "3.78" valid float number:  false

var input = '31237.78';
var result = isFloat(input);
console.log('Is '+ input + ' valid float number: ', result);
// Output
Is "31237.78" valid float number:  true

var input = '317.78';
var result = isFloat(input);
console.log('Is "'+ input + '" valid float number: ', result);
// Output
Is "317.78" valid float number:  true




Monday, 26 September 2016

AngularJS filter to Translate input and replace variable separately afterwards into the translated input

Translate input and replace the variable afterwards on the string with variable placeholder ie. [variable].

First create AngularJs filter fiel called translate-input-var-and-replace.js and save with below content:
/* Translate input and replace the variable afterwards on the string with variable placeholder ie. [variable]. */
myapp.filter('translateInputWithVarReplace', ['$filter', function($filter) {
    return function(input, replaceVariable) {
        input = $filter('translate')(input);
        return input.replace(RegExp(/\[(.*?)\]/g), replaceVariable);
    };
}]);


Usage:
// The 'translated_string' should have the value containing the [variable] in the string. 
// translated_string = 'There will be [variable] people watching this movie.';

 var output = $filter('translateInputWithVarReplace')('translated_string', '545');

Expected Output:
There will be 545 people watching this movie.

Merging two or more JavaScript Objects using AngularJS

Please use below steps to merge two or more JavaScript Objects using AngularJS

// Object one
var jsObjectA = {title:'Buddha is born in Nepal', famous:'Gautum Buddha', country:'Nepal', district:'Bhirawa'};

// Object two
var jsObjectB = {religion:'Buddhism', zone:'Lumbini', district:'Kapilvastu'};

// Merging above two objects
var mergeObject = angular.extend({}, jsObjectA, jsObjectB); 

Expected Output:
{title:'Buddha is born in Nepal', famous:'Gautum Buddha', country:'Nepal', religion:'Buddhism', zone:'Lumbini', district:'Kapilvastu'};

Tuesday, 30 August 2016

AngularJS String Replace filter in the Template File

Please find follow the below steps to replace the string on the Template file using AngularJS filter:

1. Create the filter file called string-replace.js and add the following code.
myapp.filter('stringReplace', [ function() {
    return function(input, search, replace) {
        input = input.split(search);
        
        var x;
        var result = '';
        var prefix = '';
        for (x in input ) {
            result += prefix + input[x];
            prefix = replace;
        }

        return result;
        //return input.replace(search, replace);
    };
}]);

2. Then, in html template file, adopt the below example to use the filer.
{{your_string_variable_here | stringReplace:'searchParameterHere':'replaceParameterHere'}}

Example:
{{"GLOBAL_WARMING_NEEDS_TO_CONTROL_BY_EVERYONE" | stringReplace:'_':'-'}}

Output: GLOBAL-WARMING-NEEDS-TO-CONTROL-BY-EVERYONE

Friday, 15 April 2016

AngularJS DataTable Plugin Rending the HTML with Angular Event Tigger such as ng-click

To make the Angular action trigger from the DataTable plugin, you just need add the below code within the loadDataTable Function.

// Define this function first.
function createdRow(row, data, dataIndex) 
{
 // Recompiling so we can bind Angular directive to the DT
 $compile(angular.element(row).contents())(scope);
}

// Then, add the below line with the "DTOptionsBuilder.newOptions()"
.withOption('createdRow', createdRow);

Please find the sample complete function with above added code.

Adding the AngurJS filter to Capitalize the first word, all words or all UPPERCASE

First, create the file 'capitalize.js' with the following contents.
/* capitalize.js file contents */

myapp.filter('capitalize', function() {
    return function(input, all) {
        var reg = (all) ? /([^\W_]+[^\s-]*) */g : /([^\W_]+[^\s-]*)/;
        return (!!input) ? input.replace(reg, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}) : '';
    };
});

Then use the below example to adopt the code in your contexts;
To Capitalize the first word only
{{name | capitalize}} 
OUTPUT: "Hello world nepal"

To Capitalize the all words
{{name | capitalize:true}} 
OUTPUT: "Hello World Nepal"

The below example is for Data Table (angular-laravel library) rending html case:
/* In Data table rending html case */

var data = 'hello world nepal';
.renderWith(function (data, type, full) {
 return $filter('capitalize')(data)
})

// OUTPUT: "Hello world nepal"

.renderWith(function (data, type, full) {
 return $filter('capitalize')(data, true)
})
// OUTPUT: "Hello World Nepal"

/* and, For UPPERCASE */
.renderWith(function (data, type, full) {
 return data.toUpperCase();
})

// OUTPUT: "HELLO WORLD NEPAL"

Thursday, 28 January 2016

Confirm Message when refresh or close or forward or backward the page via Javascript and AngularJs

To prevent accidental closing of page on the browser, you can set the Confirm Message when refresh or close or forward or backward the page via Javascript and AngularJs.

On Plain javascript, however you can also add the below code into AngularJs Controller
// Event Trigger when refreshing/Closing the page.
        var myEvent = window.attachEvent || window.addEventListener;
        var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compatable

        myEvent(chkevent, function(e) { // For >=IE7, Chrome, Firefox
            var confirmationMessage = 'Submission form not complete yet, Are you sure you want to leave this page?';  // a space
            (e || window.event).returnValue = confirmationMessage;
            return confirmationMessage;
        });        

On AngularJs State Changes, put the below code inside the particular controller.
// Event Trigger when clicking browser Back or Forward buttons
        $scope.$on('$locationChangeStart', function( event ) {
            $scope.pagePreventAlert();
            event.preventDefault();
        });

Sample AlertService 
I have created the sample AlertService AngularJs Service to prompt the alert, Please add the below factory into your code.
app.factory('AlertService', ['$rootScope', '$mdDialog', '$mdMedia',
    function ($rootScope, $mdDialog, $mdMedia) {

        var AlertService = {};

        return {

            onBeforeUnloadAlert: function(aData) {

                var data = aData;

                // Event Trigger when refreshing/Closing the page.
                var myEvent = window.attachEvent || window.addEventListener;
                var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compatable

                myEvent(chkevent, function(e) { // For >=IE7, Chrome, Firefox
                    var confirmationMessage = data.msgContent; // or a space
                    (e || window.event).returnValue = confirmationMessage;
                    return confirmationMessage;
                });

                // Event Trigger when clicking browser Back or Forward buttons
                $rootScope.$on('$locationChangeStart', function(e) {

                    // Appending dialog to document.body to cover sidenav in docs app
                    // Modal dialogs should fully cover application
                    // to prevent interaction outside of dialog
                    $mdDialog.show(
                        $mdDialog.alert()
                            //.parent(angular.element(document.querySelector('#popupContainer')))
                            .clickOutsideToClose(true)
                            .title(data.msgTitle)
                            .textContent(data.msgContent)
                            //.ariaLabel('Alert Dialog Demo')
                            .ok('Ok')
                            .targetEvent(e)
                    );

                    e.preventDefault();
                });
            }

        };

        return AlertService;
    }
])

And, in Your_Angular_Controller, please add "AlertService" on the controller parameter and include the below function it on each controller,
        // Page/Stage changes alert
        AlertService.onBeforeUnloadAlert({
            msgTitle: 'Form Submission Alert',
            msgContent: 'The Submission form not complete, please continue to submit the form or you may lose the information.'
        });

Monday, 5 October 2015

Create 'Go To Top' or 'Scroll To Top' via jQuery


Create 'Go To Top' or 'Scroll To Top' via jQuery, please follow below steps:
1. Add the below HTML code,
< div class="scroll-to-top" >
     < a href="#" id="to-top" rel="nofollow" style="outline: none;" >Top< /a >
< /div >

2. Then, include the jQuery library and add the below Javascript Code
jQuery(function($) {

    var scrollToTop = function() {
        $("a[href='#top']").click(function () {
            $("html, body").animate({scrollTop: 0}, "slow");
            return false;
        });
    }
    // Call the scroll to top function.
    scrollToTop();

});


To check whether the Jquery Library is called or not

To check whether the Jquery Library is called or not, please run below function;

if (typeof jQuery != 'undefined') {
    alert("jQuery library is loaded!");
}else{
    alert("jQuery library is not found!");
}

Tuesday, 5 May 2015

Print the HTML contents via Element Id or Class Name via Javascript/jQuery

Please use the below function to print the HTML contents via Element Id or Class Name via Javascript/jQuery.
PS: You would require jQuery library to link.
/* 
* Function to print the HTML contents via element Id or Class 
* elem This can be Name of the tag ID or Class 
*/
function PrintMe(elem) {
 
 var pageHeaderTitle = 'Enter you Page Header Title here';
 var bodyTitle = 'Enter you Page Title here';  
 var bodySubTitle = 'Enter you Page Sub Title here'; // (optional) 
 var pageData = jQuery(elem).html();
 
 var siteLogoCaption = 'Your Site Name';
 var site_logo_alt = '/images/logo/logo.jpg';
 
 var css_bootstrap_file_url = 'http://www.yourdomain.com/css/bootstrap.min.css';
 var css_custom_file_url = 'http://www.yourdomain.com/css/custom.css';
 
 var mywindow = window.open('', 'my div', 'height=600,width=800,scrollbars=yes');
 mywindow.document.write('< html>' + pageHeaderTitle + ' - <?php echo $site_name; ?>');
 mywindow.document.write('< link href="' + css_bootstrap_file_url + '" rel="stylesheet" type="text/css">');
 mywindow.document.write('< link href="' + css_custom_file_url + '" rel="stylesheet" type="text/css">');
 mywindow.document.write('< img alt="' + siteLogoCaption + '" height="auto" src="' + site_logo_url + '" style="float: left; margin-left: 40px;" width="100" />');
 mywindow.document.write('< div class="container" id="print_form" >< h3>'+ bodyTitle +'< /h3>');
 mywindow.document.write('< h4>' + bodySubTitle + '< /h4>< hr />');
 mywindow.document.write(pageData);
 mywindow.document.write('< p>---< /p>');
 mywindow.document.write('< /div>< /body>< /head>< /html>');
 mywindow.print();
 mywindow.document.close();
}

/** Invoking the printing function **/
< button class="btn btn-primary" onclick="PrintMe('#divContainerToPrint'); return false;" >Print< /button>

Monday, 28 April 2014

Prevent to change the select input value if NO to confirm via Jquery

Find the code below to prevent the Select box/Dropbox to alter the value if 'NO' to Confirm using Jquery.
 var prev_rank_val;
        $( '#rank_level_id' ).focus(function() {
            prev_rank_val = $(this).val();
        })
        .change(function() {
            $(this).blur() // Firefox fix 

            var msg = "Are you sure you want to continue?"; // message here
            var action = confirm(msg);

            if ( action==true) {
                return true;
            }
            else {
                $(this).val(prev_val); // rollback the current value if to No
                return false;
            }
        });


Friday, 10 January 2014

Bootstrap Date Picker - Auto close of Date1/ Check In and jump to Date2/ Check Out with 7days difference

In Bootstrap Date Picker, if you need to auto close a date select popup and auto jump to Date2/ Check Out popup with 7days difference, afterwards auto close the Check Out popup once selected. Use the below function.
/** Auto closing of In/Out POPUP on Select */
var enableInOutDatePicker = function (date1, date2) {
 
 // $( "#start_date" ).datepicker( { startDate:null, format:'dd/mm/yyyy', todayHighlight:true } );
 
 if ( (date1 =="" )  || (date1 == undefined) ) { var date1 = 'start_date'; }
 if ( (date2 =="" )  || (date2 == undefined) ) { var date1 = 'end_date'; }
 
 var nowTemp = new Date();
 var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
 //alert(nowTemp);

 var checkin = $('#' + date1).datepicker({

     beforeShowDay: function (date) {
         return date.valueOf() >= now.valueOf();
     }
 }).on('changeDate', function (ev) {
     if (ev.date.valueOf() > checkout.date.valueOf()) {
         var newDate = new Date(ev.date);
         newDate.setDate(newDate.getDate() + 7);
         //alert(newDate);
         checkout.setValue(newDate);
         //checkout.setDate(newDate);
         checkout.update();
     }
     checkin.hide();
     $('#' + date2).focus();
 }).data('datepicker');

 var checkout = $('#' + date2).datepicker({
     beforeShowDay: function (date) {
         return date.valueOf() > checkin.date.valueOf();
     }
 }).on('changeDate', function (ev) {
     checkout.hide();
 }).data('datepicker');
};
/** Auto closing of In/Out POPUP on Select */


Bootstrap Datepicker - Auto closing of POPUP on date selection

In the Bootstrap Datepicker, if you need to auto close of popup date selector,
please use the below function.
/** Auto closing of POPUP on single date Selection */
var enableSingleDatePicker = function (date) {
 
 if ( (date =="" )  || (date == undefined) ) { var date = 'start_date'; }
 
 var nowTemp = new Date();
 var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);

 var checkout = $('#' + date).datepicker({
     beforeShowDay: function (date) {
      return date.valueOf() >= now.valueOf();
     }
 }).on('changeDate', function (ev) {
     checkout.hide();
 }).data('datepicker');
};

Wednesday, 27 November 2013

To serialise the Input Form field by ID using Jquery

/** To serialise the Input Form field by ID using Jquery. */
var formData = new FormData(document.getElementById("fieldId"));
alert(formData);

Wednesday, 20 November 2013

Jquery function to auto scroll to the page to any position in Javascript

Please find the below function to make auto scroll of the page based on the parameter provided.

/** Auto Scroll to Top. */
var autoScrollToTop = function (value) { 
 
 //var scrollTopVal = 90; 
 if (typeof value == 'undefined') { 
  var scrollTopVal = 90;
 }
 else if ((value != "") && isNaN(value)) {
  scrollTopVal = $(value).offset().top;
 }
 else if (value > 0 ) {
  scrollTopVal = value;
 }
 //alert(scrollTopVal);
 $('html, body').animate({ scrollTop: scrollTopVal }, 500); // 500 (mili second) or 'slow'
};

// The function can be called as below;
autoScrollToTop() // Type: Blank, (Default:90)-> Scroll to 90px from top.
autoScrollToTop(0) // Type: Zero -> Top scroll to very top
autoScrollToTop(150) // Type: Numeric -> Scroll to Provided Numeric value(150px) from top.
autoScrollToTop('.className'); // Type: 'className' -> Auto calculate the distance from top to that className component
autoScrollToTop('#elementID'); // Type: 'elementID' -> Auto calculate the distance from top to that elementIDcomponent