Skip to content

Commit 677d20e

Browse files
committed
fix(material-experimental/mdc-slider): implement a better solution for change detection problem
* use markForCheck() instead of detectChanges() in updateTickMarks() * call detectChanges() once at the end of ngAfterViewInit() in MatSlider with a thorough comment explaining why it is needed
1 parent 2a98bf7 commit 677d20e

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

src/material-experimental/mdc-slider/slider-adapter.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ export class SliderAdapter implements MDCSliderAdapter {
9393
}
9494
updateTickMarks = (tickMarks: TickMark[]): void => {
9595
this._delegate._tickMarks = tickMarks;
96-
this._delegate._cdr.detectChanges();
96+
this._delegate._cdr.markForCheck();
9797
}
9898
setPointerCapture = (pointerId: number): void => {
9999
this._delegate._elementRef.nativeElement.setPointerCapture(pointerId);

src/material-experimental/mdc-slider/slider.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,17 @@ export class MatSlider implements _MatSliderInterface, AfterViewInit, OnDestroy
164164
this._foundation.layout();
165165
this._initialized = true;
166166
}
167+
// The MDC foundation requires access to the view and content children of the MatSlider. In
168+
// order to access the view and content children of MatSlider we need to wait until change
169+
// detection runs and materializes them. That is why we call init() and layout() in
170+
// ngAfterViewInit().
171+
//
172+
// The MDC foundation then uses the information it gathers from the DOM to compute an initial
173+
// value for the tickMarks array. It then tries to update the component data, but because it is
174+
// updating the component data AFTER change detection already ran, we will get a changed after
175+
// checked error. Because of this, we need to force change detection to update the UI with the
176+
// new state.
177+
this._cdr.detectChanges();
167178
}
168179

169180
ngOnDestroy() {

0 commit comments

Comments
 (0)