2

I want to display a dropdown containing (localized) month names by using angular's datepipe.

<select>
    <option *ngFor="let month of months;" value="{{month}}">
         {{month | date: 'MMMM'}}
    </option>
</select>

months is an array of numbers from 0 to 11.

The generated options have the correct values but it's always 'January'

<select>
     <option value="0"></option>
     <option value="1"> January</option>
     <option value="2"> January</option>
     <option value="3"> January</option>
     <option value="4"> January</option>
     <option value="5"> January</option>
     <option value="6"> January</option>
     <option value="7"> January</option>
     <option value="8"> January</option>
     <option value="9"> January</option>
     <option value="10"> January</option>
     <option value="11"> January</option>
</select>

Is there something wrong with my code or isn't it possible at all to achieve what i want using angular's datepipe? If so, how can i accomplish it?

TheDoctor
  • 2,362
  • 4
  • 22
  • 39

3 Answers3

7

months must be an array of Dates, you can use

months=[0,1,2,3,4,5,6,7,8,9,10,11].map(x=>new Date(2000,x,2))

And (see that I changed the [value] to [value]="i")

<select>
    <option *ngFor="let month of months;let i=index" [value]="i">
         {{month | date: 'MMMM'}}
    </option>
</select>
Eliseo
  • 50,109
  • 4
  • 29
  • 67
1

As you can read from the Angular documentation, the input for the date pipe is one of the following:

The date expression: a Date object, a number (milliseconds since UTC epoch), or an ISO string

So your input of 0-11 is interpreted as milliseconds after 01. January 1970. Thus, all of them are in January. You should probably create an array of Date objects to use as months[].

jmlr
  • 93
  • 1
  • 1
  • 7
0

I find myself generating arrays often enough in my apps that I created a to pipe:

export class ToPipe implements PipeTransform {

  transform(value: number, args?: number): number[] {
    const ret = [];
    for (let i = value; i <= args ; i++) {
      ret.push(i);
    }
    return ret;
  }
}

Angular's date pipe accepts date strings that can be constructed in html. I find this a bit more readable and it doesn't clutter up my typescript with static arrays:

<select>
  <option *ngFor="let monthNum of 1 | to : 12" [value]="monthNum">{{('2020-' + monthNum + '-01') | date: 'MMM'}}</option>
</select>
adamdport
  • 11,687
  • 14
  • 69
  • 91