in my app iam using my custom datetime picker(it consists of text input and material datepicker)- code looks like this:
<div fxLayoutAlign="center center" fxLayoutGap="10px" [formGroup]="form">
<mat-form-field appearance="outline" class="no-padding no-underline" [class.mat-form-field-invalid]="control?.invalid&&!control.hasError('badTime')" [class.ng-invalid]="control?.invalid&&!control.hasError('badTime')">
<mat-label>{{label}}</mat-label>
<input matInput [matDatepicker]="picker" [max]="max" [min]="min" (dateChange)="changeDate($event)" readonly formControlName="date" (focus)="picker.open()" [errorStateMatcher]="matcher">
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
<app-timepicker [test]="control" [showSeconds]="showSec" formControlName="time" [label]="label" (timeChanged)="changeTime($event)" (overMidnight)="onOverMidnight($event)"></app-timepicker>
</div>
This form control returns single value to the outside, i have recently upgraded to angular material 17, and i have problem with propagating invalid state from parent form to this form control. In previous versions i was able to propagate invalid state at least as class "mat-form-field-invalid" which i use with ngClass and switch it depends on ngControl passed to the component. This doesnt work any more. Any ideas how to pass invalid state from parent to custom form control, that will work, maybe in a more elegant way? I tried error state matcher, but the problem is, that the invalid state is on the parent form, so i cant acces it. Here is the code of component:
mport { DatePipe } from '@angular/common';
import { Component, EventEmitter, Input, OnInit, Output, forwardRef } from '@angular/core';
import { ControlValueAccessor, UntypedFormBuilder, UntypedFormGroup, NgControl, NG_VALUE_ACCESSOR, FormControl, FormGroupDirective, NgForm } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';
@Component({
selector: 'app-datetimepicker',
templateUrl: './datetimepicker.component.html',
styleUrls: ['./datetimepicker.component.scss'],
providers: [
]
})
export class DatetimepickerComponent implements ControlValueAccessor{
matcher = new MyErrorStateMatcher();
value:Date=null;
form:UntypedFormGroup=null;
onChange = (value) => {};
onTouched = () => {};
touched = false;
disabled = false;
init=false;
_disableTime=false;
_disableDate=false;
@Input('disableDate') set disableDate(value:boolean){
this._disableDate=value;
if(value){
this.form.get("date").disable();
}
else{
this.form.get("date").enable();
}
};
@Input('disableTime') set disableTime(value:boolean){
this._disableDate=value;
if(value){
this.form.get("time").disable();
}
else{
this.form.get("time").enable();
}
};
@Input() label:string;
@Input() max:Date;
@Input() min:Date;
@Input() showSec:boolean=false;
@Output() dateChanged:EventEmitter<Date>=new EventEmitter();
constructor(private fb:UntypedFormBuilder, private datePipe:DatePipe, public control:NgControl) {
if (this.control != null) {
this.control.valueAccessor = this;
}
this.form=this.fb.group({
date:[{value:null}],
time:[null]
});
console.log(this.control);
}
get errorState(): boolean {
console.log("check");
return this.control.invalid;
}
writeValue(value: Date): void {
if(value!=null){
this.value=value;
this.form.setValue({
date:value,
time:this.datePipe.transform(value,this.showSec?"HH:mm:ss":"HH:mm")
},{emitEvent:false})
}
}
registerOnChange(onChange: any) {
this.onChange=onChange;
}
registerOnTouched(onTouched: any) {
this.onTouched = onTouched;
}
markAsTouched() {
if (!this.touched) {
this.onTouched();
this.touched = true;
}
}
setDisabledState(disabled: boolean) {
this.disabled = disabled;
}
changeDate(event){
const newDate=new Date(this.value.getTime());
newDate.setDate(event.value.getDate());
newDate.setMonth(event.value.getMonth());
this.value=newDate;
this.onChange(this.value);
console.log("datechanged");
this.dateChanged.emit(this.value);
this.markAsTouched();
}
changeTime(event){
const [hours,minutes,secs]=event.split(":");
console.log(event.split(":"));
const newDate=new Date(this.value.getTime());
if(this.showSec){
newDate.setHours(hours,minutes,secs);
}
else{
newDate.setHours(hours,minutes);
}
this.value=newDate;
this.onChange(this.value);
this.markAsTouched();
}
onOverMidnight(dateChange:number){
const newDate=new Date(this.value.getTime());
if(newDate<=this.max && newDate>=this.min){
newDate.setDate(newDate.getDate()+dateChange);
this.value=newDate;
this.onChange(this.value);
this.form.patchValue({date:this.value});
}
}
}
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
console.log(control);
console.log(form);
return true;
}
}
A errorStateMatcher is an object of a class that implements ErrorStateMatcher
In a class you can pass to the constructor all the parameter that you want.
So imagine you write some like
//see that return true when the condition is
//"similar" to your control?.invalid&&!control.hasError('badTime')"
export class ErrorCustomMatcher implements ErrorStateMatcher {
constructor(private parentControl: NgControl,private notErrorkey:string) {}
isErrorState(
control: FormControl | null,
form: FormGroupDirective | NgForm | null
): boolean {
return this.parentControl.invalid &&
this.parentControl.touched &&
!this.parentControl.hasError(this.notErrorkey)?true:false
}
}
Now, in your component you declare the errorStateMatcher object
matchErrorDate=new ErrorCustomMatcher(this.control,'badTime')
And use in your input
<input matInput [errorStateMatcher]="matchErrorDate"
[matDatepicker]="picker"
...>
placeholder="pat@example.com"
[formControl]="email"
(input)="onChange(id.value)"
(blur)="onTouched()"
You can see an example in this stackblitz. See that if it's empty show an error, but if the email is not fullfilled not show an error
NOTE: Really I don't like the use of an argument like "not..." and use a comparision "!", I suggest change by an argument in positive mode, some like
constructor(private parentControl: NgControl,private errorkey:string) {}
isErrorState(...): boolean {
return this.parentControl.invalid &&
this.parentControl.touched &&
this.parentControl.hasError(this.errorkey)?true:false
}