Skip to content

feat(list): Add single select mode. #18126

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jan 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/components-examples/material/list/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,20 @@ import {MatListModule} from '@angular/material/list';
import {ListOverviewExample} from './list-overview/list-overview-example';
import {ListSectionsExample} from './list-sections/list-sections-example';
import {ListSelectionExample} from './list-selection/list-selection-example';
import {ListSingleSelectionExample} from './list-single-selection/list-single-selection-example';

export {
ListOverviewExample,
ListSectionsExample,
ListSelectionExample,
ListSingleSelectionExample,
};

const EXAMPLES = [
ListOverviewExample,
ListSectionsExample,
ListSelectionExample,
ListSingleSelectionExample,
];

@NgModule({
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/** No styles for this example. */
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<mat-selection-list #shoes [multiple]="false">
<mat-list-option *ngFor="let shoe of typesOfShoes">
{{shoe}}
</mat-list-option>
</mat-selection-list>

<p>
Option selected: {{shoes.selectedOptions.selected}}
</p>
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import {Component} from '@angular/core';

/**
* @title List with single selection
*/
@Component({
selector: 'list-single-selection-example',
styleUrls: ['list-single-selection-example.css'],
templateUrl: 'list-single-selection-example.html',
})
export class ListSingleSelectionExample {
typesOfShoes: string[] = ['Boots', 'Clogs', 'Loafers', 'Moccasins', 'Sneakers'];
}
18 changes: 18 additions & 0 deletions src/dev-app/list/list-demo.html
Original file line number Diff line number Diff line change
Expand Up @@ -162,4 +162,22 @@ <h3 mat-subheader>Dogs</h3>
<button mat-raised-button (click)="groceries.deselectAll()">Deselect all</button>
</p>
</div>

<div>
<h2>Single Selection list</h2>

<mat-selection-list #favorite
[(ngModel)]="favoriteOptions"
[multiple]="false"
color="primary">
<h3 mat-subheader>Favorite Grocery</h3>

<mat-list-option value="bananas">Bananas</mat-list-option>
<mat-list-option selected value="oranges">Oranges</mat-list-option>
<mat-list-option value="apples">Apples</mat-list-option>
<mat-list-option value="strawberries" color="warn">Strawberries</mat-list-option>
</mat-selection-list>

<p>Selected: {{favoriteOptions | json}}</p>
</div>
</div>
2 changes: 2 additions & 0 deletions src/dev-app/list/list-demo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ export class ListDemo {
this.modelChangeEventCount++;
}

favoriteOptions: string[] = [];

alertItem(msg: string) {
alert(msg);
}
Expand Down
6 changes: 6 additions & 0 deletions src/material/list/_list-theme.scss
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@
background: mat-color($background, 'hover');
}
}

.mat-list-single-selected-option {
&, &:hover, &:focus {
background: mat-color($background, hover, 0.12);
}
}
}

@mixin mat-list-typography($config) {
Expand Down
1 change: 1 addition & 0 deletions src/material/list/list-option.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
[matRippleDisabled]="_isRippleDisabled()"></div>

<mat-pseudo-checkbox
*ngIf="selectionList.multiple"
[state]="selected ? 'checked' : 'unchecked'"
[disabled]="disabled"></mat-pseudo-checkbox>

Expand Down
88 changes: 87 additions & 1 deletion src/material/list/selection-list.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,16 @@ describe('MatSelectionList without forms', () => {
expect(selectList.selected.length).toBe(0);
});

it('should not add the mat-list-single-selected-option class (in multiple mode)', () => {
let testListItem = listOptions[2].injector.get<MatListOption>(MatListOption);

testListItem._handleClick();
fixture.detectChanges();

expect(listOptions[2].nativeElement.classList.contains('mat-list-single-selected-option'))
.toBe(false);
});

it('should not allow selection of disabled items', () => {
let testListItem = listOptions[0].injector.get<MatListOption>(MatListOption);
let selectList =
Expand Down Expand Up @@ -882,6 +892,80 @@ describe('MatSelectionList without forms', () => {
expect(listOption.classList).toContain('mat-list-item-with-avatar');
});
});

describe('with single selection', () => {
let fixture: ComponentFixture<SelectionListWithListOptions>;
let listOption: DebugElement[];
let selectionList: DebugElement;

beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [MatListModule],
declarations: [
SelectionListWithListOptions,
],
}).compileComponents();

fixture = TestBed.createComponent(SelectionListWithListOptions);
fixture.componentInstance.multiple = false;
listOption = fixture.debugElement.queryAll(By.directive(MatListOption));
selectionList = fixture.debugElement.query(By.directive(MatSelectionList))!;
fixture.detectChanges();
}));

it('should select one option at a time', () => {
const testListItem1 = listOption[1].injector.get<MatListOption>(MatListOption);
const testListItem2 = listOption[2].injector.get<MatListOption>(MatListOption);
const selectList =
selectionList.injector.get<MatSelectionList>(MatSelectionList).selectedOptions;

expect(selectList.selected.length).toBe(0);

dispatchFakeEvent(testListItem1._getHostElement(), 'click');
fixture.detectChanges();

expect(selectList.selected).toEqual([testListItem1]);
expect(listOption[1].nativeElement.classList.contains('mat-list-single-selected-option'))
.toBe(true);

dispatchFakeEvent(testListItem2._getHostElement(), 'click');
fixture.detectChanges();

expect(selectList.selected).toEqual([testListItem2]);
expect(listOption[1].nativeElement.classList.contains('mat-list-single-selected-option'))
.toBe(false);
expect(listOption[2].nativeElement.classList.contains('mat-list-single-selected-option'))
.toBe(true);
});

it('should not show check boxes', () => {
expect(fixture.nativeElement.querySelector('mat-pseudo-checkbox')).toBeFalsy();
});

it('should not deselect the target option on click', () => {
const testListItem1 = listOption[1].injector.get<MatListOption>(MatListOption);
const selectList =
selectionList.injector.get<MatSelectionList>(MatSelectionList).selectedOptions;

expect(selectList.selected.length).toBe(0);

dispatchFakeEvent(testListItem1._getHostElement(), 'click');
fixture.detectChanges();

expect(selectList.selected).toEqual([testListItem1]);

dispatchFakeEvent(testListItem1._getHostElement(), 'click');
fixture.detectChanges();

expect(selectList.selected).toEqual([testListItem1]);
});

it('throws an exception when toggling single/multiple mode after bootstrap', () => {
fixture.componentInstance.multiple = true;
expect(() => fixture.detectChanges()).toThrow(new Error(
'Cannot change `multiple` mode of mat-selection-list after initialization.'));
});
});
});

describe('MatSelectionList with forms', () => {
Expand Down Expand Up @@ -1255,7 +1339,8 @@ describe('MatSelectionList with forms', () => {
id="selection-list-1"
(selectionChange)="onValueChange($event)"
[disableRipple]="listRippleDisabled"
[color]="selectionListColor">
[color]="selectionListColor"
[multiple]="multiple">
<mat-list-option checkboxPosition="before" disabled="true" value="inbox"
[color]="firstOptionColor">
Inbox (disabled selection-option)
Expand All @@ -1274,6 +1359,7 @@ describe('MatSelectionList with forms', () => {
class SelectionListWithListOptions {
showLastOption: boolean = true;
listRippleDisabled = false;
multiple = true;
selectionListColor: ThemePalette;
firstOptionColor: ThemePalette;

Expand Down
33 changes: 29 additions & 4 deletions src/material/list/selection-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import {
SimpleChanges,
ViewChild,
ViewEncapsulation,
isDevMode,
} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {
Expand All @@ -50,6 +51,7 @@ import {
setLines,
ThemePalette,
} from '@angular/material/core';

import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';

Expand Down Expand Up @@ -108,6 +110,7 @@ export class MatSelectionListChange {
// be placed inside a parent that has one of the other colors with a higher specificity.
'[class.mat-accent]': 'color !== "primary" && color !== "warn"',
'[class.mat-warn]': 'color === "warn"',
'[class.mat-list-single-selected-option]': 'selected && !selectionList.multiple',
'[attr.aria-selected]': 'selected',
'[attr.aria-disabled]': 'disabled',
},
Expand Down Expand Up @@ -255,7 +258,7 @@ export class MatListOption extends _MatListOptionMixinBase implements AfterConte
}

_handleClick() {
if (!this.disabled) {
if (!this.disabled && (this.selectionList.multiple || !this.selected)) {
this.toggle();

// Emit a change event if the selected state of the option changed through user interaction.
Expand Down Expand Up @@ -324,7 +327,7 @@ export class MatListOption extends _MatListOptionMixinBase implements AfterConte
'class': 'mat-selection-list mat-list-base',
'(blur)': '_onTouched()',
'(keydown)': '_keydown($event)',
'aria-multiselectable': 'true',
'[attr.aria-multiselectable]': 'multiple',
'[attr.aria-disabled]': 'disabled.toString()',
},
template: '<ng-content></ng-content>',
Expand All @@ -335,6 +338,8 @@ export class MatListOption extends _MatListOptionMixinBase implements AfterConte
})
export class MatSelectionList extends _MatSelectionListMixinBase implements CanDisableRipple,
AfterContentInit, ControlValueAccessor, OnDestroy, OnChanges {
private _multiple = true;
private _contentInitialized = false;

/** The FocusKeyManager which handles focus. */
_keyManager: FocusKeyManager<MatListOption>;
Expand Down Expand Up @@ -373,8 +378,25 @@ export class MatSelectionList extends _MatSelectionListMixinBase implements CanD
}
private _disabled: boolean = false;

/** Whether selection is limited to one or multiple items (default multiple). */
@Input()
get multiple(): boolean { return this._multiple; }
set multiple(value: boolean) {
const newValue = coerceBooleanProperty(value);

if (newValue !== this._multiple) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think about only doing this check in dev mode?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

if (isDevMode() && this._contentInitialized) {
throw new Error(
'Cannot change `multiple` mode of mat-selection-list after initialization.');
}

this._multiple = newValue;
this.selectedOptions = new SelectionModel(this._multiple, this.selectedOptions.selected);
}
}

/** The currently selected options. */
selectedOptions: SelectionModel<MatListOption> = new SelectionModel<MatListOption>(true);
selectedOptions = new SelectionModel<MatListOption>(this._multiple);

/** View to model callback that should be called whenever the selected options change. */
private _onChange: (value: any) => void = (_: any) => {};
Expand All @@ -397,6 +419,8 @@ export class MatSelectionList extends _MatSelectionListMixinBase implements CanD
}

ngAfterContentInit(): void {
this._contentInitialized = true;

this._keyManager = new FocusKeyManager<MatListOption>(this.options)
.withWrap()
.withTypeAhead()
Expand Down Expand Up @@ -589,7 +613,7 @@ export class MatSelectionList extends _MatSelectionListMixinBase implements CanD
if (focusedIndex != null && this._isValidIndex(focusedIndex)) {
let focusedOption: MatListOption = this.options.toArray()[focusedIndex];

if (focusedOption && !focusedOption.disabled) {
if (focusedOption && !focusedOption.disabled && (this._multiple || !focusedOption.selected)) {
focusedOption.toggle();

// Emit a change event because the focused option changed its state through user
Expand Down Expand Up @@ -642,4 +666,5 @@ export class MatSelectionList extends _MatSelectionListMixinBase implements CanD

static ngAcceptInputType_disabled: BooleanInput;
static ngAcceptInputType_disableRipple: BooleanInput;
static ngAcceptInputType_multiple: BooleanInput;
}
4 changes: 3 additions & 1 deletion tools/public_api_guard/material/list.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ export declare class MatSelectionList extends _MatSelectionListMixinBase impleme
color: ThemePalette;
compareWith: (o1: any, o2: any) => boolean;
disabled: boolean;
multiple: boolean;
options: QueryList<MatListOption>;
selectedOptions: SelectionModel<MatListOption>;
readonly selectionChange: EventEmitter<MatSelectionListChange>;
Expand All @@ -116,7 +117,8 @@ export declare class MatSelectionList extends _MatSelectionListMixinBase impleme
writeValue(values: string[]): void;
static ngAcceptInputType_disableRipple: BooleanInput;
static ngAcceptInputType_disabled: BooleanInput;
static ɵcmp: i0.ɵɵComponentDefWithMeta<MatSelectionList, "mat-selection-list", ["matSelectionList"], { "disableRipple": "disableRipple"; "tabIndex": "tabIndex"; "color": "color"; "compareWith": "compareWith"; "disabled": "disabled"; }, { "selectionChange": "selectionChange"; }, ["options"]>;
static ngAcceptInputType_multiple: BooleanInput;
static ɵcmp: i0.ɵɵComponentDefWithMeta<MatSelectionList, "mat-selection-list", ["matSelectionList"], { "disableRipple": "disableRipple"; "tabIndex": "tabIndex"; "color": "color"; "compareWith": "compareWith"; "disabled": "disabled"; "multiple": "multiple"; }, { "selectionChange": "selectionChange"; }, ["options"]>;
static ɵfac: i0.ɵɵFactoryDef<MatSelectionList>;
}

Expand Down