角度自由文本日期选择器,将自动填充斜杠(月/日/年)



我在弹出窗口中使用日期选择器 (ng-bootstrap(,我希望此字段还允许用户手动插入日期 (MM/DD/YYYY(,但不是要求用户输入斜杠,而是应该自动填充斜杠。

Angular 8 和@ng-bootstrap/ng-bootstrap,我在 keyup 事件上编写了一个处理程序,试图附加斜杠并将值设置为表单,但它不允许我,我尝试删除表单控件上的验证器,因此验证仅在用户完全输入日期而不是部分输入后发生。

我已经在键控事件上创建了处理程序

<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};
}
}
}

但是表单值在两个输入值后重置,12重置为"(空(,但组件中的var具有值12/

我想在用户输入两个值和四个值示例后自动填充日期字段 (MM/DD/YYYY( => 的斜杠,12使其进入12/然后用户继续12/2012/20/用户继续12/20/2019

要执行 setValue 或 patchvalue,格式必须是 json,日期月份和年份而不是字符串,这就是它变空的原因。

例如:

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

我们可以通过使用指令和主机侦听器来做到这一点

@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 + '/');
}
}
}

您可以在 https://medium.com/@victor.loh95/create-date-masking-custom-directive-for-ngbdatepicker-ff4cc73097c1

最新更新