Using forEach with switch cases in Angular5 (TypeScript)

I am trying to work with a basic array of languages and a switch function, but I am having trouble using the forEach method on the cases. It would be really helpful as there are numerous languages in the world! ;)

public languages = ["en", "de"];
public selectLanguage: string = "en";

changeLanguageSelect() {
    switch (this.selectLanguage) {
        case "en":
            this.translate.use('en');
            break;
        case "de":
            this.translate.use('de');
            break;
    }
}

I don't have much else to add. Essentially, I want to iterate through the languages array in a similar way.

Answer №1

Make use of the provided array of permitted languages by simply verifying if the current language is included in the array:

if (languages.includes(currentLanguage)) {
   this.translate.use(currentLanguage);
}

Hence, there is no necessity for a loop in this scenario.

Answer №2

Instead of using a switch statement, why not utilize the language accept type of the browser to automatically set the target language for translation based on the user's preference? Then, provide a select list of other languages for users to choose from as an alternative option.

An interesting idea would be integrating Angular with Google Translate... :) Perhaps you are overcomplicating the issue at hand. Another approach could involve utilizing Internationalization (i18n) pipes in Angular - see Angular il8n docs

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

Strategies for incorporating a JSON variable into the HttpClient query parameters in an Ionic 5 application

Currently using Ionic 5 and attempting to retrieve the IP address of the client user to include it in a URL. Here is my code: this.ipclient = this.httpClient.get("https://api.ipify.org/?format=json"); this.ipclient .subscribe(ipclient => { console.log( ...

The type 'Observable<unknown>' cannot be assigned to type 'Observable<Something>'

I am a beginner with Angular and Firebase, facing an issue while attempting to import of from rxjs and returning null using switchMap in my auth.service.ts. import { ActivatedRoute } from '@angular/router' import { Observable, of } from 'r ...

Utilizing cellRendererParams in Ag-Grid version 19 with Angular 6 to execute a function within my component

One issue I encountered in my Ag-grid column was when I added a component that required calling a function from my controller. While I could access the controller without any issues, attempting to call another function proved problematic. This occurred bec ...

The act of importing the MatButtonModule module serves no purpose

I am developing an Angular application with the Material design framework. My goal is to incorporate the material button module into my project. Including it in app.module.ts is done as follows (excerpt from code): import { MatTableModule } from '@ ...

Routing through routers and closing modals

Within my Angular project, I am using a form component across two separate components. What I want is for the onSubmit function to close a modal if the user selects 'Save' in one component, and to navigate using the router link if it's in th ...

Ultimate combo: React, TypeScript, and Vite for seamless imports!

Problem The issue I'm facing is related to my React app built with the command yarn create vite. I tried to switch to using absolute imports instead of "../../.." in my files, but unfortunately it doesn't seem to work in my React + Vi ...

What is the process for transforming a TypeScript Node.js project into a standalone .exe executable file?

Currently, I am in the process of compiling my TypeScript project into JavaScript to eventually convert it into an executable file. I have experimented with various tools like https://github.com/nexe/nexe, https://github.com/vercel/pkg, and . My usage of ...

The rule result is invalid due to the occurrence of the Function()

As I proceed with the upgrade from angular 6 to angular 7, I am diligently following the guidelines provided on the official Angular website. Upon executing the command to update angular/cli and core for version 7: $ ng update @angular/cli@v7 @angular/c ...

What is the method for retrieving a child element from a TemplateRef variable?

I'm currently working with a component that has a modal feature. The modal is enclosed within an <ng-template> element. <ng-template #modalm let-modal> ... <button type="button" (click)="onSubmit()" class="bt ...

Using Angular 5 custom validations in combination with Bootstrap 4 validation pseudo-classes (:valid, :invalid)

Bootstrap 4 validation styles are based on the classes form-control:valid and form-control:invalid. Angular provides the option to apply any custom class when a field is in error. If I adhere to the specifications outlined here: https://getbootstrap.com/d ...

Function in Typescript that can return multiple data types

I recently started learning about TypeScript and its concepts. During my practice sessions, I encountered a problem that left me puzzled. There is a function named `functionA` which returns an object based on the response received from an API. type Combina ...

How can CSS variables be applied to a hover property within an Angular directive?

Check out the directive below: import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: 'd-btn', host: {} }) export class ButtonDirective { constructor(private el: ElementRef){} @HostLis ...

How can typescript configurations be imported/exported in a node environment?

I'm encountering difficulties while trying to set up a TypeScript node project and import modules: Below is the structure of my project: /build /src main.ts ...

What is the process of unloading pages in Angular 2?

In the process of developing an Angular 2 application consisting of approximately 200 pages, we have considered various loading strategies such as lazy loading, eager loading, and pre-loading. A question that arises is whether a page that has been lazily ...

Authenticating to Google APIs using Node.js within a lambda function: A step-by-step guide

I'm encountering an issue when trying to connect a Google sheet to an AWS Lambda function. While the code runs smoothly during local testing, upon deployment to the function, I receive an error message indicating that the credentials.json file cannot ...

Tips for simulating Firebase authentication providers like FacebookAuthProvider?

My goal is to create a mock for the firebase.auth object in react-native-firebase, specifically targeting the signInWithCredential method. This mock will allow me to test my code effectively. The code I am testing looks like this: public async FacebookSi ...

What could be causing the validation form error in my Angular application?

My Angular form includes a validation feature for input fields. Specifically, I am trying to validate the address field with the following line of code: <span *ngIf='submitted && f["caddress"].errors' class="invalid-feedback" ...

ASP.Net Core 3.1 server receives a blank user in JWT Bearer token

Today, I've been working on integrating JSON Web Token information with HttpContext.User using the Microsoft.AspNetCore.Authentication.JwtBearer library. The Issue: Whenever I make a request to the server, I can access functions with the [Authorize] ...

Exploring Immediately Invoked Function Expressions in TypeScript

I came across an interesting article on self-invoking functions in JavaScript by Minko Gechev. This article teaches us how to create a JavaScript function that calls itself immediately after being initialized. I am curious about how we can achieve this in ...

Issue with missing support-v4.jar in Nativescript Angular

I'm currently testing out a groceries sample using Nativescript with Angular and Typescript. I followed the instructions from this link Encountering the following error: FAILURE: Build failed with an exception. * What went wrong: An issue occurre ...