Switch up the Angular base URL using ngx-translate

I successfully integrated ngx-translate into my Angular project. Now, I want to dynamically change the base href based on the language selected from the header menu.

Currently, the URL appears as: "localhost:4200". However, upon launching the project, it should display either as "localhost:4200/en" or "localhost:4200/es", depending on the chosen language.

In my index.html file, I have the following:

<base href="/"/>

The header component's TypeScript file contains a function that switches the language using ngx-translate. Although 'replaceState' was used to reflect the chosen language in the URL, it reverts back when navigating to another route.


import { Component, OnInit } from '@angular/core';
//For translate language
import { TranslateService } from '@ngx-translate/core'; 
import { Router, Event, NavigationStart, NavigationEnd } from '@angular/router';
import { Location } from '@angular/common';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss'],
})
export class HeaderComponent implements OnInit {


  constructor(private translate: TranslateService,
              private router: Router,
              private location: Location,
              ) 
    { translate.addLangs(['es','en']);
      translate.setDefaultLang('es'); 
    }

  ngOnInit(): void {



  }


  useLanguage(language: string): void {
    this.translate.use(language); 
    // alert(language);

    // location.replace("https://www.google.com");
    // return;


    const modified_path = language;
    this.location.replaceState(modified_path);

  } 
 

}



Answer №1

It appears that you are trying to implement routing using base href in your application. I recommend utilizing base href only for scenarios where multiple instances of the application are required, each housed within a subfolder.

If you are looking to have just one instance of the application handling different languages, consider exploring Angular Router (https://angular.io/guide/router-reference). The approach involves creating a route at the root level representing the language and employing a language guard to ensure only valid languages are accessed.

const routes: Routes = [
    {
        path: ':language',
        canActivate: [LanguageGuard],
        children: [
            {
                path: 'home',
                component: HomeComponent,
            },
            {
                path: 'some-page',
                component: SomePageComponent,
            },
        ]
    },
    {
        path: '**',
        redirectTo: '/en',
    },
];

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

Utilizing GraphicsMagick with Node.js to Extract Page Frames from Multi-Page TIF Files

I am currently working with a JavaScript script that can successfully convert a single page TIF file to JPEG. However, I am facing difficulties in determining whether "GraphicsMagick For Node" (https://github.com/aheckmann/gm) has the capability to extra ...

Uncertainty surrounding dynamic bootstrapping in @NgModules

After successfully installing rc7, my module and component are functioning as expected. Now, I am looking to utilize it on a webpage by only bootstrapping modules and components if the current page contains the necessary selector. Although I have declare ...

Acquire Base64 Representation from an HTTP Call

I'm looking for a solution to convert an image from a URL into a base64 string using two functions: getImageAsBlob and toBase64. The former uses HttpClient to fetch the image as a Blob, while the latter converts the retrieved Blob into a base64 string ...

Compose a tweet using programming language for Twitter

How can I send a message to a Twitter user from my .NET application? Are there any APIs or JavaScript code that can help with this task? Any assistance would be greatly appreciated. ...

Error Loading Chunks in Angular ThreeJS Application Specifically in Safari

I've been working with ThreeJS in Angular. After compiling and uploading the latest version of my app to the server last week, I encountered the following errors on Mac and iPhone: SyntaxError: Left hand side of operator '=' must be a refere ...

What is the best way to trigger a jQuery UI dialog using an AJAX request?

My website includes a jQuery UI Dialog that opens a new window when I click the "create new user" button. Is there a way to open this window using an AJAX request? It would be useful if I could open the dialog-form from another page, such as dialog.html ...

What is the simplest method for comparing transaction amounts?

I'm in the process of integrating PayPal into my website using their REST API. My goal is to allow users to input the amount they want to deposit. While I can obtain the total during payment creation, I'm unsure how to smoothly pass it to the exe ...

Do you notice a discrepancy in the number returned by Javascript's Date.getUTCDate() when the time component is set to

Consider the following code snippet: const d = new Date('2010-10-20'); console.log(d.getUTCDate()); If you run this, the console will output 20. However, if you modify the code like so: const d = new Date('2010-10-20'); d.setHours(0, ...

Using Typescript to enclose the object and selectively proxying a subset of its methods

When utilizing the Test class within another class named Wrapper, I aim to be able to delegate the methods to the test instance in a universal manner, like so: this.test[method](). In this scenario, my intention is only to delegate the fly, swim, and driv ...

Can Vue.js be configured to reload specific components only?

Can a specific component be reloaded in a Vue component that contains multiple components? For example, if there is a component structured like this: Main component <template> <button>Button<button> <component1></component> ...

Creating a new Express JS application

I've encountered an issue with my express application. When I run the server and navigate to localhost in my browser, the index page loads but without the image that should be displayed. The browser console shows a 404 error for the image URL. GET ht ...

Surveillance software designed to keep tabs on how long visitors remain on external websites

My goal is to increase sign-ups on my website by providing users with a unique JavaScript snippet to add to their own sites. I have two specific questions: 1) If I implement the following code to track visit duration on external websites, how can I ensure ...

Obtain the HTTP response status code within a middleware function

I am currently developing an application where I want to create a custom logging system for every request made. For each request, I want to log the timestamp, method, route, and the response code sent to the client. Here is the code I have at the moment: ...

Choosing a value type within an interface or object declaration

Is it possible to extract a nested type object from an interface or parent type? interface IFake { button: { height: { dense: number; standard: number; }; }; otherStuff: string; } type Button = Pick<IFake, 'button'& ...

Make sure to switch up the font color with each new use of the "append" function

Currently, on my page, I am using the append function to add a new line of text (".newText") every 5 seconds. This is my current implementation: var fontColors var randomColor $(function(){ fontColors = ['red','orange','yello ...

Is there a method to restrict the scope of identical components appearing multiple times on a single page in Angular 7?

I have a scenario where I need to place multiple instances of the same component on a page, but when one of them receives input and refreshes, all other components also refresh. Is there a way to prevent this from happening? <tr *ngFor="let map of imgs ...

What does the error message "JSON.parse: unexpected character at line 1 column 1 of the

In the process of developing a node.js module that involves importing a JSON file: const distDirPath = "c:/temp/dist/"; const targetPagePath = "c:/temp/index.html"; const cliJsonPath = "C:/CODE/MyApp/.angular-cli.json"; const fs = require('fs'); ...

Instructions for importing a CSV file into PostgreSQL with Node.js

Just dipping my toes into the world of node js. I've got a csv file sitting on my local system that I'm eager to upload to my local PostgreSQL Database using node js. Here's what I've been experimenting with: var csv = require(' ...

Font size for the PayPal login button

I am looking to adjust the font size of the PayPal Login button in order to make it smaller. However, it appears that the CSS generated by a script at the bottom of the head is overriding my changes. The button itself is created by another script which als ...

Traveling within a layered object

Currently, I'm working with an object and iterating through it to retrieve outputs as shown below: var obj = { "first": { "Bob": { "1": "foo", "2": "bar" }, "Jim": { "1": "baz" } }, "second": { "Bob": { ...