From b50b225e5c13287a04541f17e1a511c6374569b9 Mon Sep 17 00:00:00 2001 From: David Reher Date: Wed, 2 Aug 2017 19:23:24 +0200 Subject: [PATCH] feat(select): custom text for multiple selected values add input property to set a callback which will display a custom text if multiple values are selected. Similar to MdAutocomplete.displayWith. fixes #6218 --- src/lib/select/select.spec.ts | 36 +++++++++++++++++++++++++++++++++++ src/lib/select/select.ts | 7 +++++++ 2 files changed, 43 insertions(+) diff --git a/src/lib/select/select.spec.ts b/src/lib/select/select.spec.ts index 2b00b161f9db..40ad9aa66519 100644 --- a/src/lib/select/select.spec.ts +++ b/src/lib/select/select.spec.ts @@ -2435,6 +2435,42 @@ describe('MdSelect', () => { expect(trigger.textContent).toContain('Tacos, Pizza, Steak'); }); + it('should display a custom text if multipleDisplayWith is set', () => { + testInstance.select.multipleDisplayWith = (values: string[]): string => { + return `${values.length} selected` + }; + trigger.click(); + fixture.detectChanges(); + + const options = overlayContainerElement.querySelectorAll('md-option') as + NodeListOf; + + options[0].click(); + options[2].click(); + options[5].click(); + fixture.detectChanges(); + + expect(trigger.textContent).toContain('3 selected'); + }); + + it('should only affect the text if multipleDisplayWith is set', () => { + testInstance.select.multipleDisplayWith = (values: string[]): string => { + return `${values.length} selected` + }; + trigger.click(); + fixture.detectChanges(); + + const options = overlayContainerElement.querySelectorAll('md-option') as + NodeListOf; + + options[0].click(); + options[2].click(); + options[5].click(); + fixture.detectChanges(); + + expect(testInstance.control.value).toEqual(['steak-0', 'tacos-2', 'eggs-5']); + }); + it('should throw an exception when trying to set a non-array value', async(() => { expect(() => { testInstance.control.setValue('not-an-array'); diff --git a/src/lib/select/select.ts b/src/lib/select/select.ts index 989d79db0536..11138a35e398 100644 --- a/src/lib/select/select.ts +++ b/src/lib/select/select.ts @@ -318,6 +318,9 @@ export class MdSelect extends _MdSelectMixinBase implements AfterContentInit, On this._multiple = coerceBooleanProperty(value); } + /** Function that maps the selected values to (a single) display value in the trigger. */ + @Input() multipleDisplayWith: ((viewValues: any[]) => string) | null = null; + /** Whether to float the placeholder text. */ @Input() get floatPlaceholder(): FloatPlaceholderType { return this._floatPlaceholder; } @@ -531,6 +534,10 @@ export class MdSelect extends _MdSelectMixinBase implements AfterContentInit, On if (this._multiple) { let selectedOptions = this._selectionModel.selected.map(option => option.viewValue); + if (this.multipleDisplayWith) { + return this.multipleDisplayWith(selectedOptions); + } + if (this._isRtl()) { selectedOptions.reverse(); }