我正在更新P-calendar模型值onblur事件,即使formcontrol在模型更新后有效,但表单验证会抛出false。
HTML
<form (ngSubmit)="onSubmit()" [formGroup]="form" class="box-model form-support-margin">
<div class="col-md-10 col-sm-12 col-xs-12">
<p-calendar [(ngModel)]="tbDate" [dateFormat]="dateFormat"
[showIcon]="true" formControlName="tbDate" readonlyInput="false"
(onBlur)="tbDateChange($event)">
</p-calendar>
</div>
</form>
component.ts
import { Component, OnInit, EventEmitter, Pipe, ChangeDetectorRef, Input } from "@angular/core";
import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
import * as moment from 'moment'
import { Router } from '@angular/router';
@Component({
templateUrl: "address.component.html",
})
export class AddressComponent implements OnInit {
constructor( private fb: FormBuilder){}
ngOnInit() {
this.initFormGroup();
}
initFormGroup() {
this.form = this.fb.group({
tbDate: new FormControl(this.tbDate|| '', Validators.required);
});
}
tbDateChange(event: any) {
let time = event.srcElement.value;
let d = new Date();
this.tbDate=d;
}
}
答案 0 :(得分:1)
p-calendar
自动验证输入日期时使用斜杠'/',这使得表单也有效。因此,我使用此功能来解决您的问题,让用户手动输入日期。
在我的示例中,'/'会在用户输入月和日之后自动添加。我还添加了输入验证,以便只输入数字。
HTML:
<form (ngSubmit)="onSubmit()" [formGroup]="form" class="box-model form-support-margin">
<div class="col-md-10 col-sm-12 col-xs-12">
<p-calendar [dateFormat]="dateFormat" [(ngModel)]="modelVal"
[showIcon]="true" formControlName="tbDate" [readonlyInput]="false"
(keydown)="onlyNumbers($event)"
(keyup)="addSlash($event)">
</p-calendar>
</div>
<p></p>
<button md-raised-button color="primary" type="submit" class="" [disabled]="!form.valid">Save</button>
</form>
TS:
dateFormat: = "mm/dd/yy"
constructor( private fb: FormBuilder){}
ngOnInit() {
this.initFormGroup();
}
initFormGroup() {
this.form = this.fb.group({
tbDate: new FormControl(this.tbDate|| '', Validators.required);
});
}
addSlash($event){
if(event.code != "Backspace" && (event.srcElement.value.length == 2 || event.srcElement.value.length == 5)){
event.srcElement.value += '/';
}
}
onlyNumbers(event){
if(event.code == "Backspace"
|| event.code == "ArrowLeft"
|| event.code == "ArrowRight"){
return true;
}
if(event.srcElement.value.length < 10){
if((event.keyCode >= 48 && event.keyCode <= 57)
|| (event.keyCode >= 96 && event.keyCode <= 105))
return true;
else
return false;
}
else
return false;
}
}
希望此解决方法可以解决您的问题:)