Skip to content

Commit bb9da60

Browse files
crisbetojelbourn
authored andcommitted
refactor(selection-model): expose source model in change event (#9288)
Exposes the selection model that dispatched an event inside the event itself. This is mostly for convenience, because it allows the consumer to access the selected value and other properties without having to reach outside the callback. Relates to the discussion in #8599.
1 parent 278e25a commit bb9da60

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

src/cdk/collections/selection.spec.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,19 @@ describe('SelectionModel', () => {
8585
});
8686

8787
describe('onChange event', () => {
88+
it('should return the model that dispatched the event', () => {
89+
let model = new SelectionModel();
90+
let spy = jasmine.createSpy('SelectionModel change event');
91+
92+
model.onChange!.subscribe(spy);
93+
model.select(1);
94+
95+
let event = spy.calls.mostRecent().args[0];
96+
97+
expect(spy).toHaveBeenCalled();
98+
expect(event.source).toBe(model);
99+
});
100+
88101
it('should return both the added and removed values', () => {
89102
let model = new SelectionModel();
90103
let spy = jasmine.createSpy('SelectionModel change event');

src/cdk/collections/selection.ts

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ export class SelectionModel<T> {
122122
this._selected = null;
123123

124124
if (this._selectedToEmit.length || this._deselectedToEmit.length) {
125-
const eventData = new SelectionChange(this._selectedToEmit, this._deselectedToEmit);
125+
const eventData = new SelectionChange<T>(this, this._selectedToEmit, this._deselectedToEmit);
126126

127127
if (this.onChange) {
128128
this.onChange.next(eventData);
@@ -178,11 +178,17 @@ export class SelectionModel<T> {
178178
}
179179

180180
/**
181-
* Describes an event emitted when the value of a MatSelectionModel has changed.
181+
* Event emitted when the value of a MatSelectionModel has changed.
182182
* @docs-private
183183
*/
184184
export class SelectionChange<T> {
185-
constructor(public added?: T[], public removed?: T[]) { }
185+
constructor(
186+
/** Model that dispatched the event. */
187+
public source: SelectionModel<T>,
188+
/** Options that were added to the model. */
189+
public added?: T[],
190+
/** Options that were removed from the model. */
191+
public removed?: T[]) {}
186192
}
187193

188194
/**

0 commit comments

Comments
 (0)