I'm trying to filter a list of objects within a mat-dialog popup window. I based my implementation on this very good post to avoid running Angular change detection at every keyUp event.
After implementing my filter, I verified with a console log in ngDoCheck
the change detection cycles. It appeared each keyUp event was triggering several change detection cycles.
I figured out what was the difference between the post I took as example and mine : I'm within a Material Dialog component.
I prepared a stackblitz example to show it. The FormComponent
is integrated twice, once directly in the AppComponent
and once within a mat-dialog
. Open your console and watch for the cd
and filtering
strings, which logs change detection cycles and items filtering respectively. You'll notice that when you use the dialog version, there is a very large number of cd
.
Complete code at this address
Is there a way of deactivating the change detections within the mat-dialog ? If yes, what are the side effects ?
The API of MatDialog does not contains anything that seems close to what I'm searching...
Please note that my code does execute properly, but the very high amount of change detection cycles might lower app performances on slower devices.
Hope someone can help !
Edit
Based on comments, I tried to switch ChangeDetectionStrategy to onPush
(this should not have any side effect as the binding is performed with the filtered list which is re-assigned after the debounce time). This does however not help.
I also tried to detach my component from the change detection with such code :
ngAfterViewInit() {
this.ngzone.runOutsideAngular(() => {
this.filterChangedSubscription = Observable.fromEvent(this.itemfilter.nativeElement, 'keyup')
.debounceTime(600)
.subscribe((keyboardEvent: any) => {
this.items = this.unfilteredItems.filter(
item => item.toLowerCase().indexOf(keyboardEvent.target.value.toLowerCase()) > -1
);
this.cdref.detectChanges();
});
});
this.cdref.detach();
}
I was trying to disable the detection changes for my component (holding the input triggering the filter), but it seems the change detection hooks to be still called several time at each keyUp
event.
I suspect mat-dialog
component to register itself to keyUp
events for accessibility shortcuts and triggering change detection. Feel free to share your thoughts.