Reputation: 95
My lack of knowledge in Angular 2 and typescript led me to this issue :
I want a datatable (already imported well) with all the months of the year on abscissa, and some DB objects on the ordinate (this is OK).
I don't know how and where to declare my list of months and how to browse it in my html. A this moment, I have this :
Component.ts :
public months= {
1:'Janvier',
2:'Février',
3:'Avril',
etc...
12:'Decembre'
};
Component.html
<td *ngFor="let month of months">{{month}}</td>
Could you help me making it work (displaying at least a raw of months) and as clean as possible ? I'm pretty sure declaring a list of months directly in the class is not a good thing...
Thank you for reading
Upvotes: 1
Views: 2300
Reputation: 2099
Why not just use indexing in your view?
In your TS:
months = ["Janvier", "Février", "Avril"...];
In your HTML:
<div *ngFor="let month of months; let i = index">
<p>Month(string): {{month}}</p>
<p>Month(number): {{i+1}}</p>
</div>
Upvotes: 0
Reputation: 41571
Alternatively, you can use this way
months= [
{ 'id' :1 , 'name':'Janvier'},
{ 'id' :2 , 'name':'Février'},
{ 'id' :3 , 'name':'Avril'}
];
Accessing it in the ngFor as below
<div *ngFor="let month in months">
{{month.name}}</div>
</div>
Upvotes: 2
Reputation: 5532
You have to make an array of months. Currently you have an object.
public months = ["Janvier", "Février", "Avril"...];
Or if you really want to have an object, you can implement custom pipe:
import { Injectable, Pipe } from '@angular/core';
@Pipe({
name: 'keyObject'
})
@Injectable()
export class KeyObjectPipe {
transform(value, args:string[]):any {
let keys = [];
for (let key in value) {
keys.push({key: key, value: value[key]});
}
return keys;
}
}
And then you can use it as:
<td *ngFor="let month of months | keyObject">{{month.value}}</td>
Upvotes: 4