I am new to externalizing code. As I was working on developing a month picker in Angular, I initially had an array of months with hardcoded names in my typescript file:
arr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
Upon the advice of a senior developer, I was recommended to externalize these names in a separate JSON file for easy modification in the future. Let me walk you through my updated code.
monthpicker.component.ts
import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
...
})
export class MonthpickerComponent implements OnInit {
constructor(private translate: TranslateService){
}
//arr = ['Jan', 'Feb', ... 'Nov', 'Dec'];
monthArray = []; /* USING A DIFFERENT EMPTY ARRAY INSTEAD*/
translateCard(): void {
this.translate
.get([
'Months.January',
'Months.February',
...
'Months.December'
])
.subscribe(translations => {
this.monthArray.push(translations['Months.January']);
this.monthArray.push(translations['Months.February']);
...
this.monthArray.push(translations['Months.December']);
});
console.log(this.monthArray);
}
ngOnInit(): void {
this.translateCard();
}
/* CODE TO READ MONTH NAMES AND RENDER IN HTML*/
n = 4;
matrix: any = Array.from({ length: Math.ceil(this.monthArray.length / this.n) }, (_, i) => i).map(i =>
this.monthArray.slice(i * this.n, i * this.n + this.n).map(x => ({
monthName: x,
isSelected: false
}))
);
...
}
monthpicker.component.html
<div *ngFor="let row of matrix" class="my-table">
<span *ngFor="let x of row">
<span class="month-name">
{{ x.monthName }}
</span>
</span>
</div>
Lastly, here is the content of en-US.json
{
"Months": {
"January": "Jan",
"February": "Feb",
...
"October": "Oct",
"November": "Nov",
"December": "Dec"
}
}
After running the code, I did not encounter any errors or warnings in the console. Surprisingly, console.log(this.monthArray[])
also displays all the months correctly. However, the month-picker panel on the front-end appears blank. It seems there is an issue with the asynchronous call:
ngOnInit(): void {
this.translateCard();
}
Despite trying various solutions, including utilizing translate.instant(), the panel still remains blank. I am unsure where I have gone wrong in my implementation. Any guidance would be greatly appreciated.