Prevent Component Reloading in Angular 4 when revisiting the page

My application consists of three main components: 1) Map 2) Search 3) User Profile

Upon logging in, the MAP component is loaded by default. I can navigate to other screens using the header menu link.

I am looking to implement a feature where the map component does not reload when I return to it from another screen or using the back button. Currently, every time I come back to the map screen, all pushpins and related data are reloaded, resetting the user's last view on the map.

Please note that the map is loaded on the ngOnIt event within the map component.

How can I achieve this functionality in Angular 2/4?

A sample screenshot is attached for reference:

Answer №1

Here is the process I followed to achieve this.

To begin - I integrated the RouteReuseStrategy interface.

import {RouteReuseStrategy, ActivatedRouteSnapshot, DetachedRouteHandle} from '@angular/router';

export class CustomReuseStrategy implements RouteReuseStrategy {

    handlers: {[key: string]: DetachedRouteHandle} = {};

    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        //console.debug('CustomReuseStrategy:shouldDetach', route);
        return !!route.data && !!(route.data as any).shouldDetach;
    }

    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
        //console.debug('CustomReuseStrategy:store', route, handle);
        this.handlers[route.routeConfig.path] = handle;
    }

    shouldAttach(route: ActivatedRouteSnapshot): boolean {
        //console.debug('CustomReuseStrategy:shouldAttach', route);
        return !!route.routeConfig && !!this.handlers[route.routeConfig.path];
    }

    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
        //console.debug('CustomReuseStrategy:retrieve', route);
        if (!route.routeConfig) { return null; }
        return this.handlers[route.routeConfig.path];
    }

    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        //console.debug('CustomReuseStrategy:shouldReuseRoute', future, curr);
        return future.routeConfig === curr.routeConfig;
    }

}

Next - I included the CustomReuseStrategy provider in the app.module.

import {RouteReuseStrategy} from '@angular/router';
import {CustomReuseStrategy} from './Shared/reuse-strategy';

providers: [
{ provide: RouteReuseStrategy, useClass: CustomReuseStrategy }
]

Lastly - I added the shouldDetach attribute in app.routing.ts

import { Routes, RouterModule } from "@angular/router";
import { MapComponent } from './components/map/map.component';

const ROUTES: Routes = [
{ path: 'maps', component: MapComponent , canActivate:[AuthGuard], data: { shouldDetach: true} },
];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using typescript for Gnome shell extension development. Guidelines on importing .ts files

I'm currently working on a gnome shell extension using typescript, but I've encountered issues when trying to import .ts files. The Gnome shell documentation suggests configuring the tsconfig file as outlined in this Gnome typescript docs: { &q ...

I'm curious about how to link a JSON field using dot notation in Angular 12 HTML

Does anyone know how to bind a JSON field using dot paths in Angular 12 HTML? For example: //Angular data: any = { name: 'x1', address: { city: 'xyz' } }; field: any = 'address.city'; //Html <input [(ngModel)]="data[ ...

What kind of ng-template is used for enforcing strict typing in Angular?

I have an Angular application running on version 14, and let's consider a component inside it where I have the following HTML: <button (click)="myfn(template)">Click Me</button> <ng-template #template> <some html here& ...

Application: The initialization event in the electron app is not being triggered

I am facing an issue while trying to run my electron app with TypeScript and webpack. I have a main.ts file along with the compiled main.js file. To troubleshoot, I made some edits to the main.js file to verify if the "ready" function is being called. ...

Bespoke Socket.io NodeJS chamber

I am currently developing an application involving sockets where the requirement is to broadcast information only to individuals within a specific room. Below is a snippet of the code from my server.ts file: // Dependencies import express from 'expre ...

What is the correct way to format React's dispatch function in order to utilize a "then" method similar to a Promise?

I'm working on a simple app that dispatches an action upon first load to populate the store. However, I'm facing an issue with trying to run a then method on dispatch, as typescript is throwing errors. (As per redux's documentation, the ret ...

Make the download window appear automatically when downloading a file

How can I use JavaScript/TypeScript to prompt the browser to open the download window? My goal is to give users the ability to rename the file and select the download folder, as most downloads are saved directly in the default location. This is how I curr ...

Angular Form: displaying multiple hashtags within an input field

Utilizing Angular CLI and Angular Material, I have created a form to input new hashtags. I am facing difficulty in displaying previously added hashtags in the input field. Below is the code I have written: form.component.html <form [formGroup]="crea ...

Guide to loading a minified file in Angular 2 with Gulp Uglify for TypeScript Bundled File minimization

In my Angular 2 application, I have set the TypeScript compiler options to generate a single outFile named Scripts1.js along with Scripts1.js.map. Within my index.html file: <script src="Scripts/Script1.js"></script> <script> ...

Securing Angular2 Routes with Role-Based Authentication

I am striving to develop an AuthGuard function that verifies a user's access to a specific route based on their role and the requested route. If the user has the appropriate role for the route, they should be allowed to proceed; otherwise, they should ...

After upgrading from Angular 7 to 12, the module './rest.service.interface' does not export 'RestService' (imported as 'RestService'), causing it to not be found

Hey everyone, I've been struggling with a problem for hours now and I can't seem to fix it. Here is the interface I'm working with: import { HttpClient } from '@angular/common/http'; import { Response } from '@angular/http&apo ...

Testing the submission event on a reactive form in Angular

Scenario In my component, I have a basic form implemented using reactive forms in Angular. My objective is to test the submission event of this form to ensure that the appropriate method is executed. The Issue at Hand I am encountering challenges in tri ...

Type of event target MouseEvent

I am currently working on a custom hook const hasIgnoredClass = (element: Element, ignoredClass: string) => (element.correspondingElement ? element.correspondingElement : element ).classList.contains(ignoredClass); const isInIgnoredElement = ( ...

Entering the appropriate value into an object's property accurately

I am currently facing an issue with typing the value needed to be inserted into an object's property. Please refer below. interface SliceStateType { TrptLimit: number; TrptOffset: number; someString: string; someBool:boolean; } inter ...

Learn how to incorporate the dynamic array index value into an Angular HTML page

Exploring Angular and facing a challenge with adding dynamic array index values in an HTML page. Despite trying different solutions, the answer remains elusive, as no errors are being thrown. In TypeScript, I've initialized an array named `months` wh ...

What is the best way to inform TypeScript when my Type has been altered or narrowed down?

In my application, I have a class that contains the API code: export class Api { ... static requestData = async ( abortController: React.MutableRefObject<AbortController | null> ) => { // If previous request exists, cancel it if ...

The lib.dom.d.ts file is seriously lacking in many key components

Are there any updated versions of lib.dom.d.ts? The current one is missing a lot of essential information, causing numerous compilation errors. For example, consider this line: window.File && window.FileReader && window.FileList && ...

`Is it possible to animate the rotation of an image within an input control?`

After coming across this helpful answer, I successfully added a rotating GIF image as an icon inside an INPUT control on its right side. Simply applying the "busy" class to my control did the trick, and now it looks like it's in progress. input.busy { ...

Please input the number backwards into the designated text field

In my react-native application, I have a TextInput where I need to enter numbers in a specific order such as 0.00 => 0.01 => 0.12 => 1.23 => 12.34 => 123.45 and so on with each text change. I tried using CSS Direction "rtl" but it didn't work as expec ...

The JokesService (?) has encountered dependency resolution issues that Nest is unable to resolve

Currently delving into the world of NestJS and feeling a bit perplexed about the workings of "modules". In my project, I have two modules namely JokesModule and ChuckNorrisApiModule. My goal is to utilize the service provided by ChukNorrisService within th ...