如何填充数组以显示值已外部化的下拉列表 [角度]



我想我还没有很好地理解外化概念。我有一个简单的下拉列表,其选项存储在相应的打字稿文件中。

.HTML

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

打字稿

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

但现在我决定将所有价值观外化。

en-Us.json

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

打字稿

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();
}
}

问题在于填充我的选项数组。这就是为什么我的下拉列表是空的。它没有显示任何选项。我之前也犯了类似的错误,但那是其他一些组件而不是 Dropdown。我想我误解了这个概念。

您当前的尝试存在许多问题。

  1. 首先,下载所有必要的依赖项:

    "@ngx-translate/http-loader": "4.0.0" 
    "@ngx-translate/core": "11.0.1",
    
  2. 接下来,在 app.module 中设置加载器

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

    定义加载程序

    export function HttpLoaderFactory(httpClient: HttpClient) {
    return new TranslateHttpLoader(httpClient);
    }
    
  3. 在 app.component.ts 中确定哪个[lang].json文件 您需要加载

    constructor(private translate: TranslateService) {
    translate.setDefaultLang("en");
    translate.use("en");
    }
    
  4. 现在在组件中确定 i18n 文件中的哪些是必需的。

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

    并在模板上使用translate管道将价值观国际化

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

上述步骤的工作堆栈。

最新更新