I have checked all other questions that are related to mine but couldn't find the proper one.
I am using NgDatePicker in an Agular project with pop-up calendar selection. As place holder getting today's date as a Date type and pipe it with
'EEEE, MMMM, d, y'
My HTML code
<div class="input-group">
<input class="form-control" placeholder="{{todayDate | date : 'EEEE, MMMM, d, y'}}" name="dp" [(ngModel)]="dateCal" ngDatePicker #d="ngDatePicker" (ngModelChange)="changeDate()">
</div>
changeDate() is just triggering other functions to get data from DB according to the new selected date but I couldn't pipe the new selected date. It shows always as: 2021-08-09.
What I have tried: instead of [()] just used with [ngModel]="dateCal | date: 'EEEE, MMMM, d, y'"
and in the changeDate($event) tried to update dateCal but it's not changing the selected date format as I expected.
My .ts:
dateCal: any;
changeDate() {
this.dateCal = new Date(this.dateCal.getYear, this.dateCal.getMonth, this.dateCal.getDay)
... other functions
}
when this function is triggered, dateCal will be also updated like above but on change, it's updated in ts but in the HTML not. I'm doing something very wrong but I couldn't find it.
Thank you in advance.
Kind regards,
CodePudding user response:
This can be done but in a complex way, so to format the date based on your own custom formating , NgDatePicker datepickers use custom date adapter and formatter. The custom NgbDateAdapter lets you use your own model i.e. the structure of ngModel. The custom NgbDateParserFormatter lets you use your own formatter or parser i.e. the date format in input field.
Example
/**
* This Service handles how the date is rendered and parsed from keyboard i.e. in the bound input field.
*/
@Injectable()
export class CustomDateParserFormatter extends NgbDateParserFormatter {
readonly DELIMITER = '/';
parse(value: string): NgbDateStruct | null {
if (value) {
let date = value.split(this.DELIMITER);
return {
day: parseInt(date[0], 10),
month: parseInt(date[1], 10),
year: parseInt(date[2], 10),
};
}
return null;
}
format(date: NgbDateStruct | null): string {
//this is where you can fromat the date
const dates = new Date(
date.day this.DELIMITER date.month this.DELIMITER date.year
);
return dates.toDateString();
}
}
Please see the format
date function I have added it as an example but you need to check and test the dates are passed properly
For your easiness, I have created stackblitz link to show how it will work