Steps to implement the click functionality on the alert controller and modify the language in Ionic 4

I am currently developing a multilingual Ionic 4 app and have implemented the alert controller to display language options. However, I am facing an issue on how to dynamically change the language based on user selection.

Below is my app.component.ts code snippet:

language: any = 'en';
constructor(private translate: TranslateService) {
    this.initializeApp();
}

initializeApp() {
   this.platform.ready().then(() => {
    this.translate.addLangs(['en', 'fr']);
    this.translate.setDefaultLang('en');
    const browserLang = this.translate.getBrowserLang();
    this.translate.use(browserLang.match(/en|fr/) ? browserLang : 'en');
   });
}

 async changeLanguage() {
    const alert = await this.alertController.create({
      header: 'Language',
      inputs: [{
        type: 'radio',
        label: 'English',
        value: 'en',
        checked: this.language === 'en'
      }, {
        type: 'radio',
        label: 'French',
        value: 'fr',
        checked: this.language === 'fr'
      }],
      buttons: [{
        text: 'Cancel'
      }, {
        text: 'OK',
        handler: selectedLanguage => {
          this.language = selectedLanguage;
        }
      }]
    });
    await alert.present();
  }

Here's the relevant section in app.component.html:

<button ion-button icon-end (click)="changeLanguage()">
    <span>{{language | uppercase }}</span>
    <ion-icon name="arrow-dropdown"></ion-icon>
</button>

Upon App launch, English is set as the default language and I aim to update it dynamically based on user's choice from the alert prompt.

The use of ngx-translate plugin has been integrated into the project structure.

Shown below is the configuration within app.module.ts:

import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';

export function HttpLoaderFactory(httpClient: HttpClient) {
  return new TranslateHttpLoader(httpClient, './assets/i18n/', '.json');
}

@NgModule({
  imports: [
    TranslateModule.forRoot({
      loader: {
          provide: TranslateLoader,
          useFactory: HttpLoaderFactory,
          deps: [HttpClient]
      }
  }) ],
})

The initial language preference is English.

To utilize the translation pipe {

{ 'ACCOUNT_TAB_LAB' | translate }}
in HTML files, one must import
import { TranslateService } from '@ngx-translate/core';
in all sub-modules, which may not be optimal. Would creating a service for this purpose be recommended?

Any guidance or assistance would be greatly appreciated.

Answer №1

If you approach the problem from this angle, you might find a solution.

Dealing with missing 'translate' pipe error in Ionic 4

This method is highly effective for implementing click functionality and language translation.

Your question should be resolved by following these steps.

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

Creating dynamic captions in an Angular grid is an essential feature for enhancing the

Is there a way in Angular to dynamically update the grid titles based on an array of elements in the model? How can I display them as captions? For instance, imagine we are currently in week 202010. I would like to automatically generate the next five wee ...

transitioning from angular cli version 1.7 to version 12

Looking for a detailed guide on upgrading from version 1.7 to the latest Angular version (12/11)? I currently have an app running on version 1.7 and couldn't find a step-by-step process here: upgrading angular Would it be safe to assume that the upgr ...

An email value being recognized as NULL

create-employee.html <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <span><input type="text" [required]="!standingQueue" class="form-control" name="exampleInputEmail1" ...

Angular 2 Mixup: Using Leaflet and Google Maps with Incorrect Tile Order

I am encountering an issue while working on Leaflet and Google within Angular 2. The problem lies in the Tilemill tiles not rendering properly as they are displaying in a strange order. Here is a screenshot of the current state: https://i.stack.imgur.com/ ...

Display full lines of nested tree view HTML lists upon hovering using HTML, CSS, Angular, and Bootstrap

I currently have an Angular 4 application where a left-side div displays a tree of items as recursive HTML lists. The issue I am facing is that long texts within this div get cut off by the right border, with a scrollbar appearing instead. What I would lik ...

What steps should I take to resolve the issue of 'unable to locate the name 'OktaAuthService' error?

I am currently trying to incorporate authentication into an Angular application using Okta. I have carefully followed the step-by-step instructions provided in the documentation at this link: . However, I am encountering an error when attempting to start t ...

Tips for sending an optional parameter to @Directives in Angular 2 using TypeScript

Here is a helpful guide on passing parameters to Angular 2 directives. <p [gridGroup]="gridGroup"></p> My goal is to have the parameter as optional so that it doesn't have to be included in every class referencing the html source. Curre ...

Issue encountered when using Angular CLI to generate new files in the current directory

I've encountered an issue where, when using Angular CLI to generate components, it places them in the App folder instead of the current directory. For example, if I navigate to App/Recipe and run "ng g c recipe-item", the component will be generated i ...

Discover the power and ease of combining Angular with OIDC Implicit Flow for seamless

I have integrated the angular-auth-oidc-client package for authentication in my Angular application with our OIDC server. While using the implicit flow, some users face log out issues when the access token expires. To address this, I decided to implement t ...

There was an issue when attempting to create a unique component with the TAB feature in Angular Material

Looking to implement a custom TAB component using Angular Material 9. Here is the code snippet for creating a TAB with Angular Material: <mat-tab-group> <mat-tab label="First"> Content 1 </mat-tab> <mat-tab label=" ...

Assets failing to duplicate during ng build in production

Currently, I'm developing an application using Angular 4. I recently added a new SVG image to the assets/images folder and made the necessary changes in the angular-cli.json file as well. When I run 'ng build' locally, it successfully copies ...

Unable to assign the selected attribute to a dynamically loaded Ion-select component in Ionic 2

I'm facing an issue with dynamically loading <ion-select> and setting default selection using the selected attribute. It doesn't seem to work as expected. Can anyone help me understand why? You can view the code on Plunker app/home.page.h ...

Leveraging the power of Chart.js and Ng2-Chart within the Cumulocity platform

I'm currently in the process of developing an Angular application for the Cumulocity IoT platform and I wanted to incorporate custom bar charts using Chart.js. Initially, I faced some challenges with this setup but after some research, I came across n ...

Avoiding an event from spreading in Angular

I am working on a navigation setup that looks like this: <a (click)="onCustomParameters()"> <app-custom-start-card></app-custom-start-card> </a> When the user clicks on the app-custom-start-card, the onCustomParame ...

Include the circle.css file in the Angular 4 project by loading it in the head section of the

I am currently working with Angular 4 and would like to incorporate the circle.css styles from cssscript. After downloading the file from the provided link, I placed the circle.css within my something component file. However, when attempting to use &l ...

Error: The terminal reports that the property 'then' cannot be found on the data type 'false' while trying to compile an Angular application

In my Angular application, which I initiate through the terminal with the command ng serve, I am encountering build errors that are showing in red on the terminal screen. ✔ Compiled successfully. ⠋ Generating browser application bundles... Error: s ...

Is it possible to dynamically pass a component to a generic component in React?

Currently using Angular2+ and in need of passing a content component to a generic modal component. Which Component Should Pass the Content Component? openModal() { // open the modal component const modalRef = this.modalService.open(NgbdModalCompo ...

There was an issue encountered while trying to use HTTPS with a self-signed certificate from a

I made the switch to using https for my nodejs server by following these steps: const https = require('https'); const privateKey = fs.readFileSync('sslcert/server.key', 'utf8'); const certificate = fs.readFileSync('sslc ...

One server hosts several Angular applications on an IIS website

Is it possible to host multiple independent angular applications on a single IIS virtual directory? For instance: mysite.com/admin mysite.com/sales mysite.com/inventory The issue arises when hosting with folders as the URLs to inner pages do not ...

Best approach for managing Angular dependencies: Is it acceptable to link to a TypeScript file other than its corresponding component.ts in a component.html file?

My friend and I recently had a disagreement about a file in our project called experiment-row.component.html. The code in question looked like this: *ngIf="experimentsPageService.isRegularStatusIconVisible(experiment)" I argued that it is not go ...