In my application, I am facing an issue with a date calendar picker input that is storing dates on a server and returning them onInit
. The problem arises when the date is not stored or picked, as it returns 01/01/0001 numbers. My goal is to have the input either empty or display a placeholder like dd/mm/yyyy if no date has been selected or saved on the server yet. To achieve this, I created a custom pipe, but I am encountering difficulties when trying to implement it with ngModel
.
The error message I receive states that the value is undefined.
Here is the relevant HTML code:
<div class="form-group">
<label for="motDate">MOT Date</label>
<input type="text" class="form-control" placeholder="dd-mm-yyyy" ngbDatepicker #d="ngbDatepicker" (focus)="d.open()" #motDate>
<input type="hidden" [ngModel]="model.motDate | dateNotEmpty" (ngModelChange)="onMOTDateSelected($event)" name="motDate" />
</div>
This is the Component Typescript code:
export class VehicleFormComponent implements OnInit {
@ViewChild('motDate') motDatePicker;
ngOnInit() {
// Displaying dates from the server in the correct format using moment
this.motDatePicker.nativeElement.value = `moment(this.model.motDate).format('DD/MM/YYYY');`
}
onMOTDateSelected(e) {
this.model.motDate = new Date(e.year.toString() + '-' + e.month.toString() + '-' + e.day.toString());
}
}
And here is the Custom Pipe implementation:
import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({
name: 'dateNotEmpty',
pure: false
})
export class DateNotEmptyPipe extends DatePipe implements PipeTransform {
transform(value: any, format: string): any {
if (value.indexOf('0001') > -1) {
return "";
} else {
return new DatePipe('en-GB').transform(value, format);
}
}
}