import { AfterViewInit, Directive, ElementRef, OnDestroy } from '@angular/core'; import flatpickr from 'flatpickr'; import type { Instance } from 'flatpickr/dist/types/instance'; import { Portuguese } from 'flatpickr/dist/l10n/pt'; @Directive({ selector: '[datepicker]' }) export class DatePickerDirective implements OnDestroy, AfterViewInit { #instance!: Instance; constructor( public el: ElementRef ) { } ngAfterViewInit() { const dateFormat = 'd/m/Y'; this.#instance = flatpickr(this.el.nativeElement, { dateFormat: dateFormat, locale: Portuguese, allowInput: true }); this.el.nativeElement .addEventListener('input', () => { const value = this.el.nativeElement.value; if (value.length < 1) return; const parsedDate = this.#instance.parseDate(value, dateFormat); if(!parsedDate) return; const formattedDate = this.#instance.formatDate(parsedDate, dateFormat); if (value === formattedDate) this.#instance.setDate(value, false, dateFormat); }, true); } ngOnDestroy() { this.#instance?.destroy(); } }