I have an angular date picker within a reactive form with a required validator. The problem is that it is always not valid, even when a date is picked. Strangely the control does not display red when it is invalid. Do I need to do some manual css rules for this? HTML and Typescript below. A stackblitz of the issue is here https://stackblitz.com/edit/angular-ewa1kj-vv5baj?file=app/input-error-state-matcher-example.ts
I’ve tried with a without an errorStateMatcher on the date picker — same result
Thanks
Pete
HTML:
JavaScript
x
20
20
1
<form [formGroup]="ticketForm" class="example-form" (ngSubmit)="submitForm()">
2
<div formGroupName="systemForm">
3
<div fxLayout="column" fxLayoutAlign="left center" fxLayoutGap="15px">
4
<mat-label>Lateral: *</mat-label>
5
<mat-radio-group name="lateral" required formControlName="lateral">
6
<mat-radio-button value=1>Yes</mat-radio-button>
7
<mat-radio-button value=2>No</mat-radio-button>
8
</mat-radio-group>
9
<mat-form-field appearance="outline">
10
<mat-label>Mark Date</mat-label>
11
<input matInput [matDatepicker]="pickerMarkDate" required [errorStateMatcher] = matcher>
12
<mat-datepicker-toggle matSuffix [for]="pickerMarkDate"></mat-datepicker-toggle>
13
<mat-datepicker #pickerMarkDate></mat-datepicker>
14
</mat-form-field>
15
</div>
16
</div>
17
/*same result with and without the errorStateMatcher*/
18
<button type="submit" mat-stroked-button>Submit</button>
19
</form>
20
TypeScript:
JavaScript
1
19
19
1
export class InputErrorStateMatcherExample {
2
@Input() markDateValid: string;
3
@Input() lateralValid: string;
4
ticketForm = new FormGroup({
5
systemForm: new FormGroup({
6
lateral: new FormControl('', [Validators.required]),
7
pickerMarkDate: new FormControl('', [Validators.required])
8
})
9
});
10
11
matcher = new MyErrorStateMatcher();
12
submitForm() {
13
this.markDateValid = this.ticketForm.get('systemForm').get('pickerMarkDate').valid.toString();//always false
14
console.log(this.ticketForm.get('systemForm').get('pickerMarkDate').errors);
15
this.lateralValid = this.ticketForm.get('systemForm').get('lateral').valid.toString();
16
console.log(this.ticketForm.get('systemForm').get('lateral').errors);
17
}
18
}
19
Advertisement
Answer
You must add the formControlName
directive to link to your formGroup
:
JavaScript
1
2
1
<input formControlName="pickerMarkDate" matInput [matDatepicker]="pickerMarkDate">
2