How to populate the array for a dropdown where values are externalized already [Angular]

爷,独闯天下 提交于 2019-12-25 01:13:28

问题


I think I haven't understood externalizing concepts very well. I have a simple Dropdown whose options are stored in the corresponding typescript file.

HTML

<select>
  <option *ngFor="let source of modeOptions" [value]="source">
    {{ source }}
  </option>
</select>

typescript

modeOptions= ['Calendar year', 'Current quarter', 'Rolling year'];

But now I've decided to externalize all the values.

en-Us.json

{
  "Modes": {
    "CalendarYear": "Calendar year",
    "YearToDate": "Year-to-date",
    "Rolling12Months": "Rolling 12 months",
    "CurrentQuarter": "Current quarter"
  }
}

typescript

import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Component({
    ...
})
export class TimeselectorComponent implements OnInit {

    mode = 'Calendar year';

    public sources = [];
    public modeOptions = [];

    constructor(private translate: TranslateService) {}

    translateCard(): void {
      this.translate
        .get([
          'Months.CalendarYear',
          'Months.YearToDate',
          'Months.Rolling12Months',
          'Months.CurrentQuarter'
        ])
        .subscribe(translations => {
          this.sources.push(translations['Months.CalendarYear']);
          this.sources.push(translations['Months.YearToDate']);
          this.sources.push(translations['Months.Rolling12Months']);
          this.sources.push(translations['Months.April']);
          this.sources.push(translations['Months.CurrentQuarter']);

          // PROBLEM IS HERE
          this.modeOptions = Array.from({ length: Math.ceil(this.sources.length) }, (_, i) => i).map(i =>
                    this.modeOptions.map(x => ({

                    }))
                );
          console.log("Modes are: "+this.modeOptions); //OUTPUT: Modes are: ,,,,         
            });
    }

    ngOnInit(): void {
        this.translateCard();
    }
}

The problem is with populating my array of options. That's why my dropdown list is empty. It is not showing any option. I made a similar mistake earlier also but that was some other component not Dropdown. I think I've misunderstood the concept.


回答1:


There were many issues wrong with your current attempt.

  1. First, download all necessary dependencies:

    "@ngx-translate/http-loader": "4.0.0" 
    "@ngx-translate/core": "11.0.1",
    
  2. Next, setup a loader in the app.module

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

    define the loader

    export function HttpLoaderFactory(httpClient: HttpClient) {
      return new TranslateHttpLoader(httpClient);
    }
    
  3. In the app.component.ts decide which [lang].json file you need to load

      constructor(private translate: TranslateService) {
        translate.setDefaultLang("en");
        translate.use("en");
      }
    
  4. Now in the component decide which keys from the i18n file are required.

      ngOnInit() {
        this.sources = [
          "Modes.CalendarYear",
          "Modes.YearToDate",
          "Modes.Rolling12Months",
          "Modes.CurrentQuarter"
        ];
      }
    

    and on the template make use of the translate pipe to internationalize the values.

    <select [(ngModel)]="mode" name="source">
      <option *ngFor="let source of sources" [value]="source">
        {{ source | translate }} 
      </option>
    </select>
    

Working stackblitz of the above steps.



来源:https://stackoverflow.com/questions/59385995/how-to-populate-the-array-for-a-dropdown-where-values-are-externalized-already

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!