我将ngx-bootstrap用于日期选择器,我的日期选择器输入的格式为“ dd / MM / yyyy”,如25/07/2019
因此,我创建了一个用于捕获日期的组件,并将其转换为我的响应形式(因为mysql接受date为yyyy-mm-dd)。我在输入中使用ngModel,每次用户输入值时都会进行值更改。
代码如下:
import { environment } from './../../../environments/environment';
import { Component, OnInit, Input } from '@angular/core';
import { BsDatepickerConfig } from 'ngx-bootstrap';
import { FormGroup } from '@angular/forms';
import * as moment from "moment";
@Component({
selector: 'app-input-date',
templateUrl: './input-date.component.html',
styleUrls: ['./input-date.component.css']
})
export class InputDateComponent implements OnInit {
@Input() form: FormGroup;
@Input() fieldName: string;
@Input() fieldDescription: string;
datePickerConfig: Partial<BsDatepickerConfig>;
tempDate: any ;
isInvalid: boolean;
constructor() {
this.datePickerConfig = Object.assign(
{},
{
containerClass: "theme-dark-blue",
dateInputFormat: environment.dateFormat
}
);
}
ngOnInit() {
let theDate = this.form.get(this.fieldName).value;
if( theDate != ""){
this.tempDate = moment(theDate, environment.mysqlDateFormat).format(environment.dateFormat);
}
}
get myField()
{
return this.form.get(this.fieldName);
}
// For date
onDateModelChange(event)
{
if(this.tempDate != ""){
this.form.patchValue({
[this.fieldName]: moment(this.tempDate, environment.dateFormat).format(environment.mysqlDateFormat)
});
}else{
this.form.patchValue({
[this.fieldName]: ""
});
}
console.log(this.form.get(this.fieldName).errors);
}
}
<input type="text" class="form-control mydatepicker"
placeholder="" id="mydatepicker"
[ngClass]="{'has-error': myField.touched && myField.hasError('required')}"
[(ngModel)]="tempDate" (ngModelChange)="onDateModelChange($event)" [ngModelOptions]="{standalone: true}"
[bsConfig]="datePickerConfig" bsDatepicker>
现在,如果用户忘记输入日期或输入的日期无效,则需要显示错误。我使用Validators.required设置
this.form = this.formBuilder.group({ dateOfBirth: ["", Validators.required]});
但是由于我使用ngModel,因此无法验证。我只是想知道如何在每次用户单击/输入输入(原始或脏输入)时如何使该字段得到验证
我在InputDateComponent上尝试了此代码,但始终返回null
onDateModelChange(event){
console.log(this.form.get(this.fieldName).errors);
}
如果您对日期格式有简单的解决方案,我也想知道。