The combination of ngx-translate and *ngFor is a powerful duo

Here is the code snippet I am working with:

<div *ngFor="let service of services">
    <span><img  [src]="service.imgPath" alt="{{ service.name }}"/></span>
    <h4>{{ service.name}}</h4>
    <p>{{ service.desc }}</p>
</div> 

I want to translate each service that has three parameters. In a normal scenario, I use {{ 'something' | translate }}, where "something" is stored in a .json file like this:

"something" : "translation"

My challenge now is how to apply this translation in the context of ngFor loop. It currently reads an object from .json, but I need it to work for an array of objects.

Answer №1

To start, the first step is to import ngx-translate in your app.component.ts file:

import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
....
export function HttpLoaderFactory(http: HttpClient) {
   return new TranslateHttpLoader(http);
}
...
imports: [
    ...
    TranslateModule.forRoot({
        loader: {
          provide: TranslateLoader,
          useFactory: HttpLoaderFactory,
          deps: [HttpClient]
        }
    })
]
...

Next, you will need two files under assets folder, for example en.json for English and es.json for Spanish. In en.json:

{
  "something":  "translation of something in English"
}

In es.json:

{
  "something": "translation of something in Spanish"
}

After that, in the component where your code is located:

import { TranslateService } from '@ngx-translate/core';
...
constructor(private translate: TranslateService) {
        translate.setDefaultLang('en');
}
....

Use the translation in your template like below:

<div *ngFor="let service of services">
   <span><img  [src]="service.imgPath" alt="{{ service.name }}"/></span>
   <h4>{{service.name | translate}}</h4>
   <p>{{service.desc}}</p>
</div> 

Ensure that the 'services' object contains strings that can be translated.

Answer №2

fetch and decode the translation using translate.get('jsonKey').subscribe( (response: any)=> {

services = response;

});

Note - //verify that your JSON format is accurate

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

Error in Typescript with Ionic 2 involving the MapSubscriber, lack of helpful error information

Greetings to all who come across this message. I am currently developing an app using Ionic2 where users can send image data to the server. If the server successfully receives the data, a confirmation message is displayed; otherwise, an error notification ...

Encountering difficulties when attempting to load a module with the "js" extension in a TypeScript environment

When making a GET request with Systemjs, the extension .js is not being added to the URL. These are my TypeScript Classes customer.ts import {Address} from "./Address"; export class Customer { private _customerName: string = ""; public Customer ...

Is the rxjs observable tap executed prior to the subscription being made?

After thoroughly researching the rxjs observable tap and subscribe documentation, it appears that tap is intended for managing side effects across multiple subscriptions, whereas subscribe is best suited for individual subscriptions. However, I am curious ...

Exploring the NestJS framework using mongoose schema, interfaces, and DTOs: A deep dive

As a newcomer to nestJS and mongoDB, I find myself questioning the need to declare DTO, schema, and interface for every collection we aim to store in our mongoDB. For example, I have a collection (unfortunately named collection) and this is the DTO I' ...

Issue with npm Installation on Self-hosted Azure DevOps Agent running as NetworkService

Our Azure DevOps Server is set up with self-hosted Build Agents that operate as Windows Services under the user NetworkService. Within our project, we have a .NET Application containing both public and private NuGet Packages from a self-hosted Repository, ...

Using ngFor to render elements in several table rows

Looking for a solution to display a Python list using Angular in multiple rows instead of a single table row. The current setup is showing more than 200 objects in a single row which is not ideal. List=[1,2,3,4,5, .......100} This is the HTML currently b ...

NativeScript is unable to locate any matching routes

I'm completely new to Angular and NativeScript, and I'm struggling with setting up routing. Whenever I try to navigate, I keep getting this error message: Error: Cannot match any routes. URL Segment: 'signIn' Here's the code sn ...

Make sure to search for the "Not in" condition in an Angular 2 template list

I'm currently working with a template that looks like this: <span *ngIf="item.status !=='E1' && item.status !=='B' && item.status !=='R'">{{item.status_desc}}</span> Although the ngIf condit ...

Handling errors within classes in JavaScript/TypeScript

Imagine having an interface structured as follows: class Something { constructor(things) { if (things) { doSomething(); } else return { errorCode: 1 } } } Does this code appear to be correct? When using TypeScript, I en ...

Universal Angular along with Window's Innerwidth

Utilizing Window.Innerwidth in my Angular Project has been successful, however, I encountered an issue when attempting to implement it into Angular Universal. The content within window.innerwidth does not appear in the view source. Here is a snippet of my ...

Tips for linking a column value in a data table with Angular 7

I have an application where I retrieve data in a table format. This front end of this application is built on angular7. Now, I need certain column values to be links that when clicked will display a new component. For example: Column1 Column2 ...

Angular Tutorial: Implementing Sidenav Toggling with Icons in Multiple Components

Currently, I am in the process of creating a homepage with a toggleable sidenav. I have successfully implemented the functionality, but I am facing an issue. When the sidenav is closed, I still want to display the icons on the left-hand side instead of ico ...

"Make sure to search for the absence of 'never' in your

I am working on a React component that is supposed to display the images uploaded by the user, but I'm facing an issue. The text "Image(s) loaded" is being displayed even before the user has done anything. Here are some observations: const [imageList, ...

Type determined by the variable's condition

Is there a way to dynamically select the right type from a list of types, like a "type map," by passing a variable as component props? I've been trying to implement this concept called "Conditional Types" in TypeScript, but couldn't find a soluti ...

Having difficulty triggering a click event on a website developed with Angular2+

Looking to scrape a website with C#, the site is utilizing Angular2+. I've had some success triggering clicks on buttons, links, and more. This is being done within a WinForm application using a browserObject. The issue I'm facing is: There&apo ...

Extract information from a JSON file and import it into an Angular TypeScript file

How can I retrieve data from a JSON file and use it in an Angular typescript file for displaying on web pages? this.http.get<any>('http://localhost:81/CO226/project/loginResult.json').subscribe((res: Response)=>{ }); Here ...

Error: The nested property of the dynamic type cannot be indexed

Within my coding project, I've devised an interface that includes various dynamic keys for API routes, along with the corresponding method and response structure. interface ApiRoutes { "auth/login": { POST: { response: { ...

Extracting decimal numbers from JSON data

I am currently facing an issue in my Angular project where I am attempting to read a JSON file. This file is stored in the assets folder and contains decimal values such as: { "valueA": 0.40000000000002, "valueB": 23.999999999999999 ...

A step-by-step guide on creating a user-specific signature in Node.js

Is there a way to incorporate user-generated signatures similar to how Amazon delivery personnel have recipients sign on their mobile devices using NodeJS? Any helpful resources would be greatly appreciated. I am working with Angular for the frontend and ...

The TS2769 error occurs when trying to change the react calendar due to no matching overload in the

The calendar functionality in my project was implemented using the response calendar library. Suddenly, I encountered an onChange prop error in the default code. This was working fine before. What steps should I take to resolve this issue? Here is my cod ...