I'm using the datepicker (ng-bootstrap) in a popup, I want this field also allow user to insert date manually (MM/DD/YYYY
) but instead of asking user for entering slash it should auto populate slash.
Angular 8 and @ng-bootstrap/ng-bootstrap
, I wrote a handler on keyup event trying to append slash and setting the values to form but it is not allowing me, I've tried removing the validator on form-control so validation happen only after user enter date completely rather than partial input.
I have created handler on keyup event
<div class="form-group" [ngClass]="displayFieldStyle(form,'abc')">
<div class="input-group">
<input formControlName="abc" class="form-control" ngbDatepicker
#abc="ngbDatepicker" [minDate]="minDate" [maxDate]="maxDate"
minlength="10" maxlength="10" placeholder="MM/DD/YYYY"
(keyup)="onKeyEventHandler($event)" />
<div class="input-group-append" (click)="abc.toggle()">
<span class="input-group-text"><i class="fa fa-calendar"></i>
</span>
</div>
</div>
</div>
this.memberLookupForm = this.formBuilder.group({
...
...
abc: ['', Validators.compose([Validators.required,
DateValidator.checkDateFormat])],
...
...
});
onKeyEventHandler(event: KeyboardEvent): void {
if (event.which !== 191 ) {
let currentValue= this.form.get('abc').value;
if(!(currentValue == "" || currentValue == null)){
let numChars = currentValue.length;
if(numChars === 2 || numChars === 5){
currentValue = currentValue+'/';
this.form.get('abc').setValidators(null);
this.form.controls['abc'].setValue(currentValue);
this.form.get('abc').updateValueAndValidity();
}
}
}
}
const value = c.value;
let match;
const datePattern = /^([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})$/;
if (value) {
if (typeof value === 'string') {
match = value.match(datePattern);
if (!match) {
return {'invalidDateFormat': true};
}
}
}
but form value resetting after two entering values that 12
resetting to "" (empty), but var in component have value 12/
.
I want to auto populate slash for date field (MM/DD/YYYY
) => after user enters two values and four values example that is 12
make it to 12/
then user proceed to 12/20
make it to 12/20/
user continue to 12/20/2019
.