Only reloading the current route URL once when navigating in Angular 2/4/5

My website supports multiple languages with a dropdown menu allowing users to switch between English and German.

This component in my application's footer triggers the changeLanguage() function when the language selection is changed:

     constructor(
        private pageService: PageService,
        private router: Router,
        private el: ElementRef,
        private cd: ChangeDetectorRef,
        private meta: Meta,
        private route: ActivatedRoute
    ) { }

    ngOnInit(): void {
        var nativeElement: HTMLElement = this.el.nativeElement,
           parentElement: HTMLElement = <HTMLElement>nativeElement.parentElement;
        // move all children out of the element
        while (nativeElement.firstChild) {
           parentElement.insertBefore(nativeElement.firstChild, nativeElement);
        }
        // remove the empty element(the host)
        parentElement.removeChild(nativeElement);

        this.routerSub$ = this.router.events.subscribe(event => {
           if (event != null) {
               if (event instanceof NavigationEnd) {
                   this.languageCode = SiteContext.getLanguageCode(event.urlAfterRedirects);
                   if (this.languageCode == "en" && this.selectedLanguage.name == 'Deutsch') { this.selectedLanguage = this.languages[1]; }
               }
           }
        });
    }
    ngAfterViewInit() {
    }
    ngOnDestroy() {
        if (this.routerSub$ != null) this.routerSub$.unsubscribe();
        this.subscriptions.forEach((subscription: Subscription) => { subscription.unsubscribe(); });
        this.subscriptions = [];
    }
changeLanguage(lang) {
        let langCode: string = (lang.name == 'Deutsch' ? "de" : "en");
        this.router.navigate([langCode, 'home']);
    }

Upon changing the language selection, the app should redirect to either '/de/home' or '/en/home/' and display content accordingly.

The initial language change functions perfectly, updating the URL and loading new content. However, subsequent changes do not trigger any action after running the changeLanguage() function.

It appears to be related to reusing routes in an Angular v5 build, but solutions found on Stack Overflow have not resolved the issue.

I've focused on implementing RouteReuseStrategy shouldDetach for specific routes in Angular 2, as suggested by this question. Additionally, I am integrating the CustomReuseStrategy class from that answer.

For additional context:

app.routing.ts:

const appRoutes: Routes = [
    //{ path: '', redirectTo: '/de/home', pathMatch: 'full' },
    { path: 'de/v2-home', component: HomeComponent, data: { animation: 'de/v2-home' } },
    { path: '', redirectTo: '/de/v2-home', pathMatch: 'full' },
    { path: ':lang/v2-home', component: HomeComponent, data: { animation: ':lang/v2-home' } },
];

app.module.ts:

import { RouteReuseStrategy } from "@angular/router";
@NgModule({
    [...],
    providers: [
        {provide: RouteReuseStrategy, useClass: CustomReuseStrategy}
    ]
)}
export class AppModule {
}

If there are any errors in my navigation implementation, please point them out.

Thank you.

Answer №1

To effectively change the language in your code, it is important to separate it from ngOninit(). This means you should avoid reloading the entire component just to switch languages.

A better approach is to subscribe to your route parameters using the 'ActivatedRoute' feature.

import { ActivatedRoute } from '@angular/router';

Inject it into your component like this:

constructor (private _route : ActivatedRoute){}

Then within the ngOnInit function, subscribe to the 'lang' route parameter:

ngOninit()
{
    this._route.params.
    subscribe(params => 
    {
       this.changeLanguage(params[":lang"]);
       //Remember to sanitize any incoming parameters for security reasons.
    }
}

changeLanguage(language)
{
    //Add logic here to change the language
}

The selected language choice should be passed as a parameter to the changeLanguage() function.

By the way, if you find it helpful, here is my angular 2+ boilerplate: https://github.com/oneinazillion/CEVI

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

Angular 5 failing to navigate to new page upon successful login

Implementing an authentication system using Angular 5 that utilizes Tokens has been my recent project. However, I encountered a hurdle while trying to authenticate on the login-form - it initiates the process but ends up refreshing the page instead: View ...

Connection drops unexpectedly on Azure App Service after deploying SignalR

I'm currently facing an issue with my Angular app that utilizes SignalR and .NET core in the backend. Surprisingly, everything works perfectly fine when running locally, but as soon as I deploy it to Azure App Service, the frontend establishes a conne ...

Camera Capacitor designed to eliminate popup notifications

I am utilizing Angular along with the camera plugin in Capacitor to locally save images on both desktop and tablets. I aim to utilize the CameraSource to directly access the camera or open the gallery for files without displaying a prompt. This is how my ...

Even though there is data stored in the array, the React Native array.length appears to be returning a value

I am struggling with what appears to be a simple issue, and it's frustrating that I've had to seek help for this. The problem lies in iterating through an array messages: Message[] = [...]. No matter what method of iteration I try, it doesn&apos ...

Having trouble updating properties of child components in Angular

I have a data filtering functionality where I enter values in a filter popup and successfully retrieve results. I then store this data in local storage to retain it when navigating back from another page. However, upon returning to the filter component, I ...

Implementing NgbModule.forRoot() within a component is leading to test failures

While utilizing Tooltips and Modals within a nested component, I encountered an issue in one specific component during testing. In my spec file, I included the NgbModule.forRoot() import in the testing module which caused many unit tests to fail with the f ...

Learn how to deactivate the pause button with just one click and re-enable it once the popup appears using Angular2 and Typescript

Can anyone assist with solving an issue I am facing with a timer and a pause button? I need the pause button to be disabled once clicked, until a popup appears, then it should become enabled again. My code snippet is provided below: HTML: <button md-i ...

Inconsistencies in AngularJS ng-checked functionality

Currently, I am utilizing angularjs in conjunction with an edit view for a form. My goal is to bind the values that were previously used. Below is the code/HTML snippet that I am working with. In addition to angularjs, I am also implementing typescript fol ...

Keeping track of the authentication state in AngularFire2 on page reload to verify if the user is logged

I am facing a challenge in my angular4 app that uses angularfire2. I need to determine if a user is logged in when the page loads. Logging in and out works fine, and I have set up a guard on the router to handle unauthorized access. In one example I came ...

Issue with Bootstrap's <li> element causing it to not create a new line

I am currently designing a sidebar menu and have the following code: <div class="row m-t-1 p-l-1"> <h5 class="font-bold">{{brandsTitle}}</h5> <ul class="nav nav-pills nav-stacked f-1pt2" *ngFor="let menu of brandsMenu"> < ...

Executing an API call in Angular using a for-loop

I'm working on a project where I need to make multiple API calls based on the length of a mockInput.json file. Here's how I have implemented it: api.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeade ...

Unable to retrieve user data during route navigation

In my Angular application, I have created a service called AuthService: export class AuthService { public currentUser: Subject<firebase.User> = new Subject(); public currentUserId: Subject<string> = new Subject(); constructor(pri ...

Managing form input in Ionic2 components from external sources in Angular2

Hello there, I am currently facing an issue with managing form validation along with proper styling for nested forms. Here's what I'm aiming to achieve: I have a Page that displays Tabs components with four tabs. Each tab represents a separate @ ...

Quicker component refreshing in the Angular framework

Two Angular components were created, one for adding a new post and another for displaying all posts. Clicking the create post button redirects to the PostList component, which shows all posts. To automatically load the new post without manual refreshing, w ...

Guide on crafting Mongoose query for MongoDB

In my system, I have defined two document schemas: User and Skill. Each User has a list of skills referenced in the skills attribute. Conversely, each Skill has a list of users who possess that skill referenced in the users attribute. The main goal is t ...

Methods for comparing the current date and time to a specific time stored in a database

A database table contains the following values: "295fc51f6b02d01d54a808938df736ed" : { "author" : "James Iva", "authorID" : "JBvLC3tCYCgFeIpKjGtSwBJ2scu1", "geometry" : { "latitude" : 29.4241219, "longitude" : -98.49362819999999 ...

Utilize RequireJS to load and initiate the primary ViewModel written in TypeScrypt

Recently, I started using requireJs and I'm facing a challenge. I want to load a viewmodel from my main script, App.ts, and retrieve a new instance of my viewModel: LienPdtUfActVM.ts. This is how my App.ts file looks like: declare var jQuery: JQueryS ...

Interaction between components that are not directly related as parent and child

I am eager to conduct an experiment where clicking a button in Component A triggers a function in Component B. However, I am unsure how to achieve this if the components are not directly related as parent and child elements. Any guidance on how to make t ...

How to Implement Animations with Angular 2 Directives

Incorporating a special Directive onto elements to monitor their current scroll position seems like a handy feature. Here's an example: @Directive({ selector: '[my-scroll-animation]' }) My goal is to make the element appear on screen ...

Implementing binding of JSON API responses to dropdown menus in Angular 4

In my current Angular 4 application, I am faced with the challenge of populating a dropdown menu with data from an API response. Specifically, I am struggling to retrieve the necessary information for each section from the API. The API provides data on C ...