1

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.

Milo
  • 3,365
  • 9
  • 30
  • 44
bsp
  • 11
  • 5
  • I think you are on the right track, I guess its setting the value to empty because the form became invalid – GaryB Oct 22 '19 at 12:11
  • Datepickers usually come with a configuration to set date format, check the docs for any. – sabithpocker Oct 22 '19 at 12:27
  • @GaryB how to avoid form invalid check for temporarily and add it after completing user input – bsp Oct 22 '19 at 17:48

1 Answers1

0

To do setValue or patchvalue the format must be json with date month and year not string, that is why it is getting empty.

eg :

this.form.controls['abc'].setValue({
        day: 20,
        month: 4,
        year: 1969
     });

We can do that by using directives and host listener

@HostListener('window:keydown', ['$event'])
  handleKeyDown(event: KeyboardEvent) {
    if (this.appMaskValue && (this.appMaskValue.length === 2 || this.appMaskValue.length === 5) && event.key !== 'Backspace') {
      this.renderer.setProperty(this.elRef.nativeElement, 'value', this.appMaskValue + '/');
    }
  }
}

you can find the details in https://medium.com/@victor.loh95/create-date-masking-custom-directive-for-ngbdatepicker-ff4cc73097c1

Veena K. Suresh
  • 942
  • 5
  • 16