我正在制作一个日期选择器组件,需要验证每个输入字段(月,日,年)。我希望我的日期和年份输入字段被禁用,直到月份的值有效,并且我的年份输入到禁用直到白天有效。我的表单上有一个附加到“validate”方法的click事件,该方法检查该值是否大于0或小于/等于12(有效月份值)。当我第一次单击输入字段以将值增加到1时,不会调用validate函数。但是,它适用于第二次单击。
datepicker.component.ts
import { Component, OnInit } from "@angular/core";
import { FormGroup, FormControl, Validators } from "@angular/forms";
@Component({
selector: "app-datepicker",
templateUrl: "./datepicker.component.html",
styleUrls: ["./datepicker.component.css"]
})
export class DatepickerComponent implements OnInit {
myform: FormGroup;
dayDisabled: boolean = true;
yearDisabled: boolean = true;
ngOnInit() {
this.myform = new FormGroup({
month: new FormControl('', [Validators.required]),
day: new FormControl({ value: '', disabled: true }, [
Validators.required
]),
year: new FormControl(
{ value: '', disabled: true },
Validators.required
)
});
}
get month() {
return this.myform.get("month");
}
get day() {
return this.myform.get("day");
}
get year() {
return this.myform.get("year");
}
validate() {
if (this.month.value >= 13 || this.month.value === 0 || this.month.value === null) {
this.myform.controls.day.disable();
} else {
this.myform.controls.day.enable();
}
}
}
datepicker.component.html
<form [formGroup]="myform" (keyup)="validate()" (click)="validate()">
<fieldset>
<legend>
<span *ngIf="month.dirty && day.disabled">
Please enter a valid month
</span>
</legend>
<div>
<div>
<label>
Month
</label>
<input
type="number"
min="1"
max="12"
id="month"
formControlName="month"
name="month">
</div>
<div>
<label>
Day
</label>
<input
type="number"
min="1"
max="31"
id="day"
formControlName="day"
name="day">
</div>
<div>
<label>
Year
</label>
<input
type="number"
min="1900"
max="2019"
id="year"
formControlName="year"
name="year">
</div>
</div>
</fieldset>
</form>
答案 0 :(得分:0)
通过添加&#34;输入&#34;修复它事件处理程序
<form [formGroup]="myform" (input)="validate()" (keyup)="validate()" (click)="validate()">
</form>