0

I have route :lang/dashbaord which set in the routes config.

How can I change the :lang without making my page refresh?

import 'zone.js/dist/zone';
import { Component, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter, Router, RouterModule } from '@angular/router';

@Component({
  selector: 'my-app',
  standalone: true,
  imports: [CommonModule, RouterModule],
  template: `
    <h1>Hello from {{name}}!</h1>
    <a target="_blank" href="https://angular.io/start">
      Learn more about Angular 
    </a>
    <br><a [routerLink]="['/']">/</a>
    <br><a [routerLink]="['/en/dashboard']">/en/dashboard</a>
    <hr>
    <router-outlet></router-outlet>
  `,
})
export class App {
  name = 'Angular';
}

@Component({
  selector: 'shell',
  template: `in shell <router-outlet></router-outlet>`,
  imports: [RouterModule],
  standalone: true,
})
export class ShellComponent {}

@Component({
  selector: 'dashboard',
  template: `in dashboard <button (click)="changeLang()">change lang</button>`,
})
export class DashboardComponent {
  router = inject(Router);

  changeLang() {
    // this.router.
  }
}

bootstrapApplication(App, {
  providers: [
    provideRouter([
      {
        path: ':lang',
        component: ShellComponent,
        children: [{ path: 'dashboard', component: DashboardComponent }],
      },
    ]),
  ],
});

stackblitz demo

Jon Sud
  • 10,211
  • 17
  • 76
  • 174
  • this.router.navigate(['/your-path']) – Evgeny Gurevich Jul 24 '23 at 09:14
  • See if [this post](https://stackoverflow.com/questions/35618463/change-route-params-without-reloading-in-angular-2#comment80581119_39447121) helps. You could also consider run-time translation libraries like [ngx-translate](https://www.npmjs.com/package/@ngx-translate/core) and [transloco](https://www.npmjs.com/package/@ngneat/transloco) that doesn't require a query param for the i18n code and consequently no page reload. – ruth Jul 24 '23 at 09:18
  • @EvgenyGurevich: That would trigger a page reload -> opposite of what the OP is asking. – ruth Jul 24 '23 at 09:19

1 Answers1

0

So, To change the :lang parameter in the URL without refreshing the page, you can use the Angular Router to navigate. Here I have attached the code for it,

constructor(private router: Router) { }

  changeLang() {
    this.router.navigate(['newLang', 'dashboard'], { replaceUrl: true });
  }

The {replaceUrl: true} option ensures that the URL is updated without adding a new entry to the browser history, thereby preventing a page refresh. Instead, it modifies the existing URL with the new language parameter.

I hope this is useful.