I am making a date picker component that requires validation for each input field (month, day, year). I'd like for my day and year input fields to be disabled until the month's value is valid, and my year input to disabled until day is valid. I have a click event on my form that is attached to a "validate" method, which checks to see if the value is greater than 0 or less/equal to 12 (a valid month value). When I click on the input field for the first time in order to increase the value to 1, the validate function is not called. However, it works on 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>