Showing posts with label Angular. Show all posts
Showing posts with label Angular. Show all posts

Thursday, April 25, 2024

Html JS - Handle Browser Back Button on SPA

In Single page applications, we will not have dedicated URLs. So on click of Browser Back button it will navigate us to previous page and we lost our current page changes. We can handle this with native JavaScript functions,

Create Html Page as below to mimic SPA, 


On click of each Page button, it can switch the content,




On Each Page navigation we can set the hash URL something like below using history.pushstate or location.hash



Now on click of back button use the hashchange event to detect and open the page accordingly


Here is full code:

<html>

<head>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>

</head>

<body>

    <input type="button" value="Page1" onclick="openPage('1');" />

    <input type="button" value="Page2" onclick="openPage('2');" />

    <input type="button" value="Page3" onclick="openPage('3');" />

 

    <div id="page1" class="page">Page 1 Content</div>

    <div id="page2" class="page">Page 2 Content</div>

    <div id="page3" class="page">Page 3 Content</div>

 

 

    <div id="history"></div>

</body>

 

<script>

    $(document).ready(function () {

        hideAllPages();

     });

 

    $(window).on('popstate', (e) => {

        e.preventDefault();

        var currentLocation = window.location.pathname;

        history.push(currentLocation)

    });

     window.onbeforeunload = function () {

        return "Are you sure you want to leave this page?";

     };

    addEventListener("hashchange", (event) => {

        alert("New" + event.newURL);

        alert("Old" + event.oldURL);

        var currentHash = event.currentTarget.location.hash;

        openPage(currentHash.replace("#", ""), true);

     });

    function hideAllPages() {

        $(".page").hide();

    }

    function openPage(pageId, ignoreHistoryPush = false) {

        hideAllPages();

        $("#page" + pageId).show();

        if (!ignoreHistoryPush)  //This is to not add history on everytime

            history.pushState({ page: pageId }, pageId, '#' + pageId);
            //
location.hash = pageId  //This way also can set it

    }

 

 

</script>

</html>


Friday, July 21, 2023

How to get previous page details in page change event on embedded PowerBI report

In Power Bi, there is challenge to get page details when changing the pages. In Angular/JavaScript, powerBI client provides event handling to manage this. For this page changes, we have "pageChanged" event. Below sample code will help us to get events on page changes, so that you can capture bookmark if needed on previous page names etc.,


Sample Code: 

import { service, factories } from "powerbi-client";
const powerBI= new service.Service(factories.hpmFactory, factories.wpmpFactory, factories.routerFactory);

....

let currentSelectedPage = any = null;
let pbiElement = document.getElementById(“yourdivid”);
let pbiconfig = : any = {
    type: 'report',
    hostName: "https://app.powerbi.com/",
    accessToken: "",
    embedUrl: "",
    id: "",
    settings: {
      filterPaneEnabled: false,
      navContentPaneEnabled: false
    }
  }

this.report =  powerBI.embed(pbiElement, pbiconfig);

this.report.on('pageChanged', (event) => {
      
     console.log('Page changed Old:', event.detail.oldPage);
    
    //If event.detail.oldPage is not working then go with custom logic 
    //if (this.currentSelectedPage)
    //console.log('Page changed Old:', this.currentSelectedPage.displayName);  
    //set changed page into existing variables
    //this.currentSelectedPage = event.detail.newPage;

      console.log('Page changed New:', this.currentSelectedPage.displayName);
});

Wednesday, June 22, 2022

Angular Ng Build out of memory issue

 If you come accross issue with Angular ng build in prod mode for out of memory issue, like below

Command: ng build --prod


Include command with "node --max_old_space_size=5120 ./node_modules/@angular/cli/bin/", you can increase the size however wanted. This will solve the issue, we can also update this size in environment variables of system. 

Command: node --max_old_space_size=5120 ./node_modules/@angular/cli/bin/ng build --prod



Monday, April 25, 2022

JSON Path to use in Angular Projects

How to use JSON Path to query any JSON object.

For example, consider below simple JSON, if you want to query JSON we can use simply query as this.obj.name or this.obj.id to access to the JSON

this.obj ={

   id: 1,

   "name": "balaji"

}

For array object we can use index, for ex: this.objData[0].id. For more JSON path to find we can refer https://jsonpathfinder.com/

this.objData = {

        data: [

  {

    "id": 1,

    "name": "Balajiprasad",

    "age": 18,

              "address": {

                      "state": "TN",

                       "country": "India"

                } 

 

  },

  {

    "id": 2,

    "name": "prasad",

    "age": 28,

     "address": {

                      "state": "Tx",

                       "country": "US"

                } 

  }

]}


In angular project, if we need to use JSON path dynamically then we can refer the jsonpath library Ref: https://www.npmjs.com/package/jsonpath

Steps to use,

1. Add "json-path" in package.json file under dependencies

    "dependencies": {

"jsonpath": "1.1.1"

}


2. Add reference of "json-path" directly in component. No need to specify in App.module

    import * as jp from 'jsonpath'

3. Use the JSON path in code , need to use $.. (double dots)

   let state = jp.query(this.objData, '$..data[0].address.state')

 



Monday, September 13, 2021

Browser - Change Current Geo Location

In order to test different Geo Location in browser, we have option to change location in browser. Follow below steps,

Browsers used: Chrome, IE Edge

  1. Go to Developer Tools (Click F12)
  2. Click ... Settings Icon -> More Tools -> Sensors
  3. Now in Sensors Window, Change the location as needed. You can also manage for new locations.