I am trying to create a dropdown that by default shows me the current month. This is the code I have used:
<p-dropdown
[options]="months"
[filter]="false"
filterBy="nombre"
[showClear]="true"
placeholder="Mes"
(onChange)="onChangeMonth($event)"
(onSelect)="onSelectMonth(monthFilter)"
[style]="{ width: '110px' }"
class="dropdown-gestion"
formControlName="city"
>
export class SaCalendarMonthComponent {
monthFilter: Date = new Date();
months: string[] = [
'Enero',
'Febrero',
'Marzo',
'Abril',
'Mayo',
'Junio',
'Julio',
'Agosto',
'Septiembre',
'Octubre',
'Noviembre',
'Diciembre'
];
slectedMonth: any = null;
onChangeMonth(event: any) {
this.slectedMonth = event?.value;
}
onSelectMonth(value: Date) {
this.monthFilter = value;
const month = moment(this.monthFilter).format('MMMM');
}
}
I have also tried doing it with <p-calendar> but it shows me the month number, and I need it to show me the name.
<p-calendar
[(ngModel)]="monthFilter"
view="month"
dateFormat="mm"
[readonlyInput]="true"
[keepInvalid]="true"
placeholder="Mes"
pInputNumber
[style]="{ width: '110px' }"
(onSelect)="onSelectMonth(monthFilter)"
></p-calendar>
export class SaCalendarMonthComponent {
monthFilter: Date = new Date();
onSelectMonth(value: Date) {
this.monthFilter = value;
const month = moment(this.monthFilter).format('MMMM');
}
}
How could I fix it? Thank you very much!
Alright friend. First you need to implement in your 'SaCalendarMonthComponent' class OnInit, which enables you to have function called ngOnInit, which fires automatically after rendering your component. Then you have to set there your default month. Finally, you have to add [(ngModel)] to your p-dropdown element which enables you to bind values:
export class SaCalendarMonthComponent {
monthFilter: Date = new Date();
months: string[] = [
'Enero',
'Febrero',
'Marzo',
'Abril',
'Mayo',
'Junio',
'Julio',
'Agosto',
'Septiembre',
'Octubre',
'Noviembre',
'Diciembre'
];
slectedMonth: any = null;
onChangeMonth(event: any) {
this.slectedMonth = event?.value;
}
onSelectMonth(value: Date) {
this.monthFilter = value;
const month = moment(this.monthFilter).format('MMMM');
}
async ngOnInit() {
this.slectedMonth = this.months[new Date().getMonth()]
}
}
And dropdown element here:
<p-dropdown
[options]="months"
[filter]="false"
filterBy="nombre"
[(ngModel)]="slectedMonth"
[showClear]="true"
placeholder="Mes"
(onChange)="onChangeMonth($event)"
(onSelect)="onSelectMonth(monthFilter)"
[style]="{ width: '110px' }"
class="dropdown-gestion"
>