Converting language into class components using ngx-translate in Angular

Seeking to convert the information from a table into my typescript class. The data in the table is sourced from a JSON file within the /assets directory.

Is there a method to accomplish this task? How can I categorize translation within a typescript class? PS: Kindly refrain from suggesting alternatives that involve editing the HTML, as it is not the preferred approach.

Answer №1

If you refer to the official ngx-translate documentation, it explains how you can do this by including the TranslateService in your class constructor and utilizing either of the provided methods:

constructor(private translate: TranslateService) {}

ngOnInit(): void {
  // Using `instant` function:
  const translatedValueUsingInstant = this.translate.instant(
    'KEY_STORED_IN_TRANSLATION_FILE'
  );

  // OR using `get` function:
  let translatedValueUsingGet: string;
  this.translate
    .get('KEY_STORED_IN_TRANSLATION_FILE')
    .subscribe((value) => (translatedValueUsingGet = value));
}

Answer №2

I encountered the same issue, but I managed to find a solution that resolved it.

//In my TypeScript file

translatedValue: string = 'STRING_STORED_IN_TRANSLATION_FILE'
<!-- In my HTML file -->

<li> {{ translatedValue | translate }} </li>

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

What are some strategies I can implement to effectively manage different errors and ensure the app does not crash

I came across a variety of solutions for error handling. The key concept revolves around this explanation: https://angular.io/api/core/ErrorHandler Attempts were made to implement it in order to capture TypeError, however, the outcome was not successful: ...

What is the injection token used for a specialized constructor of a generic component?

I created a versatile material autocomplete feature that I plan to utilize for various API data such as countries, people, and positions. All of these datasets have common attributes: id, name. To address this, I defined an interface: export interface Auto ...

What is the best way to adjust the size of an Angular Material Slider?

I'm attempting to insert a slider into my program, but the slider is displaying as too lengthy for the designated space. I'm curious if there's a straightforward method of adjusting its length to fit better within the container. So far, I&a ...

Issue with Socket.io: Data not received by the last user who connected

I have developed a Node.js and Express application with real-time drawing functionality on canvas using socket.io version 1.7.2. Users are divided into separate socket rooms to enable multiple teams to draw independently. However, there is an issue where t ...

What steps can I take to ensure my dynamic route functions correctly in NextJs?

// /home/[storeId]/layout.tsx import prismadb from "@/lib/prismadb"; import { auth } from "@clerk/nextjs/server"; import { redirect } from "next/navigation"; export default async function DashboardLayout({ children, params, ...

I am encountering unexpected behavior with NextJS's getInitialProps function, as it is giving me a compiler error stating "varName not found on type {}"

I seem to be stuck on a simple syntax issue while working with NextJs. I am attempting to perform dynamic server-side fetches using the getInitialProps pattern. However, the compiler is unable to recognize the return of getInitialProps in the regular func ...

Ways to rejuvenate an angular component

I am in the process of developing a mobile application using ionic 4. The app supports two languages, namely ar and en. The menu drawer is a pre-built component included within the app. In order to ensure that the drawer component displays the correct sty ...

Tips for typing a destructured object key in TypeScript

Assuming I have a query parameter from the router in my Next.js app const { query: { id }, } = useRouter(); The value of { id } is currently string | string[] | undefined. I want to send it as a parameter to another function, and I am certain that ...

"Here's a comprehensive guide on how to connect dynamic data with angular-tree-grid components

ERROR TypeError: Cannot read property 'map' of undefined Can anyone help with binding dynamic data? I'm currently using angular-tree-grid but struggling to bind dynamic data. <html> <db-angular-tree-grid (expand)= ...

Having trouble executing the typescript build task: Command 'C:Program' is not valid as an internal or external command

I'm currently working on converting typescript code to JavaScript and have been following the steps outlined in the documentation. To automate the compilation of .ts files, I set up a watch task triggered by pressing Ctrl+Shift+B. However, upon runni ...

How can we dynamically update property values in a ngFor loop by utilizing the click method?

Here is a TypeScript file I am working with: <md-card style="display: inline-block;" *ngFor="let people of peoples"> <p> {{people.name}} </p> <p *ngIf="people.showAge"> {{people.age}} </p> < ...

Create a Typescript index signature that incorporates individual generic types for each field

Many times, the keys of a record determine its value. For instance: const record = { [2]: 5, ["string"]: "otherString", ["there is"]: "a pattern" } In these instances, each key of type K corresponds to the ...

Are the maps intersecting within the field of vision?

I have 2 components in my angular application each showing a map from mapbox. Here is the code for one of the components: Component import { Component, OnInit } from '@angular/core'; import * as mapboxgl from 'mapbox-gl'; @Component( ...

Issue with Angular Compilation When Importing Library Function into Web Worker

I am facing an issue with a web worker in Angular that used to function properly in the previous versions: /// <reference lib="webworker" /> import { ParseResult } from "papaparse"; import { readCSV } from '@fireflysemantics/ ...

How to access the result without using subscribe in Angular?

I am facing unexpected behavior with a method in my component: private fetchExternalStyleSheet(outerHTML: string): string[] { let externalStyleSheetText: string; let match: RegExpExecArray; const matchedHrefs = []; while (match = this.hrefReg.exe ...

What is the best way to prevent routing to <a href="#" > in Angular 8?

When I try to use a local reference in Angular, it looks something like this: <a class="btn-floating btn-large blue" href="#">button</a> However, instead of directing me where I expect, Angular is redirecting me to another link: localhost:420 ...

In Typescript with Vue.JS, the type 'Users[]' does not include the essential properties of type 'ArrayConstructor' such as isArray, prototype, from, of, and [Symbol.species]

Embarking on my journey with typescript and vuejs, I stumbled upon a perplexing error that has halted my progress for the past 48 hours. The error message reads as: Type 'Users[]' is missing the following properties from type 'ArrayConstruct ...

Unraveling a discriminated union

I'm currently working on writing code that can handle generic discriminated unions with a type property. Imagine I have multiple discriminated unions defined as follows: interface IFoo { type: "foo"; foo: number; } interface IBar { type: "bar ...

Angular Compilation Errors Caused by Component Inheritance

My parent Component is structured like this: import { Component} from '@angular/core'; @Component({ selector: 'app-main-parent', template: '', }) export class ParentComponent { constructor(protected service) { ...

Learn how to retrieve data from the console and display it in HTML using Angular 4

Need help fetching data inside Angular4 HTML from ts variable. Currently only able to retrieve 2 data points outside the loop. Can anyone assist with pulling data inside Angular4? HTML: <tr *ngFor="let accept of accepts"> ...