我编写了一个自定义表单控件,实际上是p-calendar组件的包装器。组件定义如下所示(注意: - 我删除了一些代码以使其变得简单)
export class MyDatePickerComponent implements ControlValueAccessor, OnInit, OnChanges {
@Input() _myDate : Date;
@Input() control: FormControl;
@Input() dateFormat: string;
@Output() myDateChange : EventEmitter<Date> = new EventEmitter<Date>();
propagateChange: any = () => {};
validateFn:any;
get myDate(){
return this._myDate;
}
set myDate(val){
this._myDate = val;
this.propagateChange(this._myDate);
}
constructor() { }
//OnInit Implementation
ngOnInit() {
this.validateFn = (c: FormControl) => {
if (c.value == null) {
return null;
}
let dateErr = { invalidDate: { valid: false } };
let userDate = moment(c.value, dateFormat, true);
return userDate.isValid() ? null : dateErr;
};
}
//ControlValueAccessor Implementation
writeValue(obj:any):void {
this.myDate = obj;
}
registerOnChange(fn:any):void {
this.propagateChange = fn;
}
registerOnTouched(fn:any):void { }
validate(c: FormControl) {
return this.validateFn(c);
}
}
自定义组件的模板是:
<div class="form-group">
<div class="col-md-2 col-sm-12 col-xs-12">
<label class="control-label">Some date caption</label>
</div>
<div class="col-md-10 col-sm-12 col-xs-12">
<p-calendar [(ngModel)]="tbDate" [dateFormat]="dateFormat" [showIcon]="true" readonlyInput="false"
(ngModelChange)="tbDateChange.emit($event)">
</p-calendar>
</div>
</div>
现在,当用户在日期文本框中手动输入错误的日期值时,将调用验证程序,但validateFn中的c.value属性包含null。
最终结果是,如果文本框为空或包含无效日期,则验证程序不起作用,因为值始终为null。
是否有任何方法可以获取用户手动输入的值以执行验证并显示验证错误。
注意: - 我正在使用PrimeNG 1.0.0-RC3