Using Angular i18n to create dynamic forms from an array of objects

After receiving an object from the API, I created a form using an array of objects in TypeScript. Although the form is rendered correctly, it fails to translate when I try to localize the application.

import { SpecializedAreasComponents } from 'src/app/models/SpecializedAreasComponent';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';

@Component({
 selector: 'citation-constraint-form',
 templateUrl: './citation-constraint-form.component.html',
 styleUrls: ['./citation-constraint-form.component.scss'],
})
export class CitationConstraintFormComponent implements SpecializedAreasComponents, OnInit {
 form: FormGroup;
 @Input() data: any;
 @Output() output: EventEmitter<any> = new EventEmitter();
 @Input() errors: any = {};
 @Input() allowEdit;
 constraints: any = [];
 selectOne = [
     {
         value: '',
         description: 'Select One...',
     },
 ];
 bool = [
     ...this.selectOne,
     {
         description: 'Yes',
         value: true,
     },
     {
         description: 'No',
         value: false,
     },
 ];
 activitySectors = [
     ...this.selectOne,
     {
         value: 'industry',
         description: 'Industry',
     },
     ...
     // (Remaining code not included for brevity)   

 
<form [formGroup]="form">
  <s-row class="pad-all-none" *ngFor="let row of rows" formGroupName="constraint">
    <s-col span="4" *ngFor="let const of row">
      <fieldset>
        <label [for]="const.key" i18n>{{ const.label }}</label>
        <input
          [type]="const.type"
          [placeholder]="const.label"
          [formControlName]="const.key"
          [id]="const.key"
          *ngIf="const.type === 'text' || const.type === 'number'"
          [attr.disabled]="!allowEdit ? '' : null"
        />
        <select
          [id]="const.key"
          [formControlName]="const.key"
          *ngIf="const.type === 'select'"
          [attr.disabled]="!allowEdit ? '' : null"
        >
          <option *ngFor="let option of const.options" value="{{ option?.value }}">
            {{ option.description }}
          </option>
        </select>
        <kendo-multiselect
          [data]="const.options"
          [textField]="'description'"
          [valueField]="'value'"
          [id]="const.key"
          [formControlName]="const.key"
          [filterable]="true"
          [placeholder]="'Select Multiple'"
          *ngIf="const.type === 'multiple'"
          [attr.disabled]="!allowEdit ? '' : null"
        >
        </kendo-multiselect>
      </fieldset>
    </s-col>
  </s-row>
</form>

I am looking for suggestions on how to implement i18n in this scenario. Any advice would be greatly appreciated.

Thank you. Lucas.

Answer №1

Resolved through the utilization of the global variable $localize

The outcome of my code was:

import { SpecializedAreasComponents } from 'src/app/models/SpecializedAreasComponent';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';

@Component({
    selector: 'citation-constraint-form',
    templateUrl: './citation-constraint-form.component.html',
    styleUrls: ['./citation-constraint-form.component.scss'],
})
export class CitationConstraintFormComponent implements SpecializedAreasComponents, OnInit {
    form: FormGroup;
    @Input() data: any;
    @Output() output: EventEmitter<any> = new EventEmitter();
    @Input() errors: any = {};
    @Input() allowEdit;
    constraints: any = [];
    
    // Various arrays initialized for select options
    selectOne = [...];
    bool = [...];
    activitySectors = [...];
    federalTaxRegimes = [...];
    entityTypes = [...];
    specialProductClasses = [...];
    fiscalTypes = [...];
    constraintsTypes = [...];

    rows = [];

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            constraint: new FormGroup({ ... }),
        });
    }

    getDescFromKey(key) { ... }

    updateForm(value) { ... }

    getDescriptionForConstraintsTypes(value, type) { ... }

    ngOnInit() { ... }

    extractArray(item) { ... }
}

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

Attempting to create a TypeScript + React component that can accept multiple types of props, but running into the issue where only the common prop is accessible

I am looking to create a component named Foo that can accept two different sets of props: Foo({a: 'a'}) Foo({a: 'a', b: 'b', c:'c'}) The prop {a: 'a'} is mandatory. These scenarios should be considered i ...

Throw TypeError: The `pipe` property of `ngrx/store` is undefined during testing

Here is the code snippet from my TypeScript file: this.store.pipe(select(subscribe.getRegCategories)).pipe(takeUntil(this.ngUnsubscribe)).subscribe(data => { if (data && data.length) { this.allRegCategories = data; ...

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 ...

How can we incorporate methods using TypeScript?

I'm currently diving into TypeScript and encountering some challenges when trying to incorporate new methods into the DOM or other pre-existing objects. For instance, I'm attempting to implement a method that can be utilized to display colored te ...

Angular Universal experiences issues with route functionality after page reloads

Recently deployed an Angular Universal web app on Firebase. While all routes within the application are functioning properly, encountering errors when trying to access them externally. Below is the error message: functions: Starting execution of "ssr" ⚠ ...

Restrict the frequency of requests per minute using Supertest

We are utilizing supertest with Typescript to conduct API testing. For certain endpoints such as user registration and password modification, an email address is required for confirmation (containing user confirm token or reset password token). To facilit ...

How can the second subscription's return value be synchronously used in the first subscription in Angular 6?

Currently, I am working on an Angular 6 application and facing a scenario where I have to make multiple API calls in sequence, pass data between them, and then continue the process. For instance, in the .ts file: logout(){ this.apiService.POST({}, "logo ...

There was an error in processing node npm due to Z_DATA_ERROR with error code errno -3, indicating an

When attempting to run my TypeScript project using tsc, I encountered the following error: Found 181 errors in 4 files. Errors Files 1 node_modules/@types/eslint-scope/node_modules/@types/eslint/helpers.d.ts:1 1 node_modules/@types/eslint/hel ...

Problem with Anular5 - "this" not functioning correctly inside of ready()

I am encountering an issue in graph.component.ts this.cContainer = cytoscape ( { ready: function(e) { this._dataService.setResultData(); } }); However, I am getting the following error message: ERROR TypeError: Cannot read property &ap ...

Angular Universal does not handle serving static files

I have a straightforward Angular Universal SSR (server-side rendering) application that is functioning well. The server successfully renders the HTML, but I am encountering an issue with static assets such as fonts, images, and icons not loading via the se ...

Learn the ins and outs of utilizing *ngIf in index.html within Angular 8

Can anyone explain how I can implement the *ngIf condition in index.html for Angular2+? I need to dynamically load tags based on a condition using the *ngIf directive, and I'm trying to retrieve the value from local storage. Below is my code snippet b ...

Retrieving the value that is not currently selected in a mat-select component

In my mat-table, there is a mat-select component displayed like this: <mat-select multiple placeholder="{{element.name}}" [(value)]="selectedCol" (selectionChange)="selectionChange($event)" [disabled]="!selection.isSelected(element.id)"> & ...

I'm unable to successfully include a download link for a PDF file stored locally

Looking to provide a download link for my resume on my website. Here's the code I'm using: <a href="My Resume.pdf" class='download' download="Resume PDF">Download CV</a> Despite using what I believe to ...

Is it possible to update input form fields in an Angular application?

I am currently designing a straightforward web page featuring a modal for creating a new object named Partner and sending it to the server. The page also includes multiple input fields to showcase the newly created data. In this project, I am utilizing Ang ...

Pass a React component as a required prop in Typescript when certain props are necessary

I am currently working on a project where I need to create a custom TreeView component using React and Typescript. My goal is to have the ability to inject a template for each TreeNode in order to render them dynamically. My main challenge right now is fi ...

Developing middleware for managing event handlers

Scenario: I am tasked with managing multiple events that necessitate an "available client". Therefore, in each event handler, my first step is to attempt to acquire an available client. If no client is available, I will send a "Service unavailable" messag ...

Set the class function to be uninitialized

I'm a little unsure of my TypeScript knowledge. I have a class MyClass with a member variable that is a function, but I don't know what this function will be at compile time. I want to allow external code to set this function dynamically during r ...

`Is There a Solution When Compilation Fails?`

I keep encountering an issue when I run the command npm start. The problem seems to be originating from PancakeSwap Frontend and after several attempts, I am still unable to resolve it. Your assistance is greatly appreciated :) Below is a snippet of my Ap ...

Hovering over the Star Rating component will cause all previous stars to be filled

I'm in the process of creating a Star Rating component for our website using Angular 11. I've managed to render the 5 stars based on the current rating value, but I'm having trouble getting the hover styling just right. Basically, if I have ...

Can Angular Universal cater to dynamic content needs?

I am considering using Angular Universal for SEO optimization and social media preview purposes. While I understand that it works well with static content, my concern lies with how it handles dynamic content. Specifically, I want search engines and social ...