I am currently working on a date picker component that needs validation for the month, day, and year input fields. My goal is to have the day and year input fields disabled until the month's value is valid, and the year input field disabled until the day is valid. I have a click event on my form connected to a "validate" method. This method checks if the input value is greater than 0 or less/equal to 12 (a valid month value). Strangely, when I first click on the input field to increase the value to 1, the validate function does not run. However, it works perfectly on the second click.
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>