I am trying to implement two way data binding on a date input while applying a pipe on the model:
<!-- The name variable is retrieved within the HTML from a loop expression -->
<input matInput [matDatepicker]="datePicker" placeholder="{{label}}" formControlName="{{name}}"
[ngModel]="data[name] | date"
(ngModelChange)="handleDateChange(data[name], $event)" >
Where my component looks something like:
//...
private data: any;
constructor(private cdRef:ChangeDetectorRef) { }
handleDateChange(field: any, date: any) {
field = date; // The code is simplified, there is more handling with the date field
this.cdRef.detectChanges();
}
Based on this post, the code above works well only thanks to this.cdRef.detectChanges();
If I remove it I get the following error:
Expression has changed after it was checked
My question is more general than related specifically to the above implementation. I would like to know what are the best practices to deal with the Expression has changed after it was checked error? Is calling cdRef.detectChanges()
a good idea?