import { FormatWidth , getLocaleDateFormat } from '@angular/common' ; import { AfterViewInit , Directive , ElementRef , HostListener , Inject , LOCALE_ID , Renderer2 , } from '@angular/core' ; import 'inputmask/lib/extensions/inputmask.date.extensions' ; import Inputmask from 'inputmask/lib/inputmask' ; @ Directive ( { selector : '[kirby-input][type="date"]' , } ) export class DateInputDirective implements AfterViewInit { @ HostListener ( 'input' ) onInput ( ) { this . updateMask ( this . elementRef . nativeElement . value ) ; } private maskingElement : HTMLElement ; constructor ( private elementRef , private renderer , @ Inject ( LOCALE_ID ) private locale ) { this . elementRef . nativeElement . removeAttribute ( 'type' ) ; } ngAfterViewInit ( ) { this . initMask ( ) ; } private initMask ( ) { const inputFormat = this . getInputFormat ( ) ; const placeholder = this . getPlaceholder ( inputFormat ) ; this . renderer . setAttribute ( this . elementRef . nativeElement , 'placeholder' , placeholder ) ; new Inputmask ( 'datetime' , { inputFormat , placeholder , } ) . mask ( this . elementRef . nativeElement ) ; this . appendMaskingElement ( ) ; } private getInputFormat ( ) { const localeDateFormat = getLocaleDateFormat ( this . locale , FormatWidth . Short ) ; return localeDateFormat . toLowerCase ( ) . replace ( /d+/ , 'dd' ) . replace ( /m+/ , 'mm' ) . replace ( /y+/ , 'yyyy' ) ; } private getPlaceholder ( inputFormat ) { return this . locale === 'da' ? inputFormat . split ( 'y' ) . join ( 'å' ) : inputFormat ; } private appendMaskingElement ( ) { const wrapper = this . wrapElement ( this . elementRef . nativeElement ) ; this . renderer . addClass ( wrapper , 'date-mask-wrapper' ) ; this . maskingElement = this . renderer . createElement ( 'div' ) ; this . renderer . appendChild ( wrapper , this . maskingElement ) ; this . renderer . addClass ( this . maskingElement , 'date-mask' ) ; } private wrapElement ( element ) { const wrapper = this . renderer . createElement ( 'div' ) ; const parent = element . parentElement ; this . renderer . insertBefore ( parent , wrapper , element ) ; this . renderer . appendChild ( wrapper , element ) ; return wrapper ; } private updateMask ( value ) { if ( ! this . maskingElement ) return ; const lastNumber = value . match ( /.*?(\d)[^\d]*$/ ) ; this . maskingElement . innerHTML = value ? value . slice ( 0 , value . lastIndexOf ( lastNumber [ 1 ] ) + 1 ) : '' ; } }