Skip to content

bug(MatTable / SelectionModel): Unexpected behavior in MatTable when using selections #25846

Open
@roennibus

Description

@roennibus

Is this a regression?

  • Yes, this behavior used to work in the previous version

The previous version in which this bug was not present was

No response

Description

I'm using MatTable with selections as suggested by the documentation example with a network-backed datasource and a compareWith function for the backing SelectionModel to track selected rows by an id property.

When unselecting a row after the datasource emitted an update it may appear as if it was spontaneously re-selected after a change detection cycle.

It seems that SelectionModel is not using compareWith when attempting to remove an item from its backing Set.

Reproduction

Stackblitz

(I'm using the position property as id in the sample)

Steps to reproduce:

  1. select a row
  2. click refresh button
  3. unselect a row
  4. refresh again

Testcase for SelectionModel:

import { SelectionModel } from "@angular/cdk/collections";

describe('SelectionModel using compareWith', ()=> {
    let selectionModel: SelectionModel<{ id: string }>;
    const item = { id: 'foo' };
    
    beforeEach(() => {
        selectionModel = new SelectionModel(true, [item]);
        selectionModel.compareWith = (a, b) => a.id === b.id;
    });
    
    it('should deselect item by reference', () => {
        expect(selectionModel.isSelected(item)).toBeTrue();
        selectionModel.deselect(item);
        expect(selectionModel.isSelected(item)).toBeFalse();
    });

    it('should deselect item by value', () => {
        const value = Object.assign({}, item);

        expect(selectionModel.isSelected(value)).toBeTrue();
        selectionModel.deselect(value);
        expect(selectionModel.isSelected(value)).toBeFalse(); // <-- this fails
    });
});

Expected Behavior

Row selection in reproduction sample should not change.

SelectionModel uses a provided compareWith function when adding / removing items.

Actual Behavior

Row selection changes unexpectedly.

SelectionModel uses compareWith when adding / checking for existence but object reference when removing an item.

Environment

  • Angular: 14.2.5
  • CDK/Material: 14.2.5
  • Browser(s): Chrome 106
  • Operating System (e.g. Windows, macOS, Ubuntu): Windows 10 19043.2130

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3An issue that is relevant to core functions, but does not impede progress. Important, but not urgentarea: cdk/collectionsarea: material/table

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions