Skip to content
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

feat(select): emit change event #2458

Merged
merged 4 commits into from
Jan 12, 2017
Merged
Show file tree
Hide file tree
Changes from 2 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
11 changes: 10 additions & 1 deletion src/demo-app/select/select-demo.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
</md-card>
</div>


<md-card>
<md-select placeholder="Drink" [(ngModel)]="currentDrink" [required]="isRequired" [disabled]="isDisabled"
#drinkControl="ngModel">
Expand All @@ -34,5 +33,15 @@
<button md-button (click)="drinkControl.reset()">RESET</button>
</md-card>

<div *ngIf="showSelect">
<md-card>
<md-select placeholder="Starter Pokemon" (change)="latestChangeEvent = $event">
<md-option *ngFor="let starter of pokemon" [value]="starter.value"> {{ starter.viewValue }} </md-option>
</md-select>

<p> Change event value: {{ latestChangeEvent?.value }} </p>
</md-card>
</div>

</div>
<div style="height: 500px">This div is for testing scrolled selects.</div>
9 changes: 8 additions & 1 deletion src/demo-app/select/select-demo.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';
import {MdSelectChange} from '@angular/material';

@Component({
moduleId: module.id,
Expand All @@ -12,6 +13,7 @@ export class SelectDemo {
isDisabled = false;
showSelect = false;
currentDrink: string;
latestChangeEvent: MdSelectChange;
foodControl = new FormControl('pizza-1');

foods = [
Expand All @@ -32,8 +34,13 @@ export class SelectDemo {
{value: 'milk-8', viewValue: 'Milk'},
];

pokemon = [
{value: 'bulbasaur-0', viewValue: 'Bulbasaur'},
{value: 'charizard-1', viewValue: 'Charizard'},
{value: 'squirtle-2', viewValue: 'Squirtle'}
];

toggleDisabled() {
this.foodControl.enabled ? this.foodControl.disable() : this.foodControl.enable();
}

}
59 changes: 57 additions & 2 deletions src/lib/select/select.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ describe('MdSelect', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [MdSelectModule.forRoot(), ReactiveFormsModule, FormsModule],
declarations: [BasicSelect, NgModelSelect, ManySelects, NgIfSelect],
declarations: [BasicSelect, NgModelSelect, ManySelects, NgIfSelect, SelectWithChangeEvent],
providers: [
{provide: OverlayContainer, useFactory: () => {
overlayContainerElement = document.createElement('div') as HTMLElement;
Expand Down Expand Up @@ -1140,13 +1140,46 @@ describe('MdSelect', () => {

});

describe('change event', () => {
let fixture: ComponentFixture<SelectWithChangeEvent>;
let trigger: HTMLElement;

beforeEach(() => {
fixture = TestBed.createComponent(SelectWithChangeEvent);
fixture.detectChanges();

trigger = fixture.debugElement.query(By.css('.md-select-trigger')).nativeElement;
});

it('should emit an event when the selected option has changed', () => {
trigger.click();
fixture.detectChanges();

(overlayContainerElement.querySelector('md-option') as HTMLElement).click();

expect(fixture.componentInstance.changeListener).toHaveBeenCalled();
});

it('should not emit multiple change events for the same option', () => {
trigger.click();
fixture.detectChanges();

let option = overlayContainerElement.querySelector('md-option') as HTMLElement;

option.click();
option.click();

expect(fixture.componentInstance.changeListener).toHaveBeenCalledTimes(1);
});
});
});

@Component({
selector: 'basic-select',
template: `
<div [style.height.px]="heightAbove"></div>
<md-select placeholder="Food" [formControl]="control" [required]="isRequired">
<md-select placeholder="Food" [formControl]="control" [required]="isRequired"
(change)="changeListener($event)">
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you remove the change event and listener from the basic select component? It should only be in the new test component.

<md-option *ngFor="let food of foods" [value]="food.value" [disabled]="food.disabled">
{{ food.viewValue }}
</md-option>
Expand All @@ -1169,6 +1202,7 @@ class BasicSelect {
isRequired: boolean;
heightAbove = 0;
heightBelow = 0;
changeListener = jasmine.createSpy('MdSelect change listener');
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you remove this too?

Copy link
Member Author

Choose a reason for hiding this comment

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

Sure, done.


@ViewChild(MdSelect) select: MdSelect;
@ViewChildren(MdOption) options: QueryList<MdOption>;
Expand Down Expand Up @@ -1234,7 +1268,28 @@ class NgIfSelect {
@ViewChild(MdSelect) select: MdSelect;
}

@Component({
selector: 'select-with-change-element',
template: `
<md-select (change)="changeListener($event)">
<md-option *ngFor="let food of foods" [value]="food">{{ food }}</md-option>
</md-select>
`
})
class SelectWithChangeEvent {
foods: string[] = [
'steak-0',
'pizza-1',
'tacos-2',
'sandwich-3',
'chips-4',
'eggs-5',
'pasta-6',
'sushi-7'
];

changeListener = jasmine.createSpy('MdSelect change listener');
}

/**
* TODO: Move this to core testing utility until Angular has event faking
Expand Down
22 changes: 18 additions & 4 deletions src/lib/select/select.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@ export const SELECT_PANEL_PADDING_Y = 16;
*/
export const SELECT_PANEL_VIEWPORT_PADDING = 8;

/** Change event object that is emitted when the select value has changed. */
export class MdSelectChange {
constructor(public source: MdSelect, public value: any) { }
}

@Component({
moduleId: module.id,
selector: 'md-select, mat-select',
Expand Down Expand Up @@ -214,10 +219,13 @@ export class MdSelect implements AfterContentInit, ControlValueAccessor, OnDestr
set required(value: any) { this._required = coerceBooleanProperty(value); }

/** Event emitted when the select has been opened. */
@Output() onOpen = new EventEmitter();
@Output() onOpen: EventEmitter<void> = new EventEmitter<void>();

/** Event emitted when the select has been closed. */
@Output() onClose = new EventEmitter();
@Output() onClose: EventEmitter<void> = new EventEmitter<void>();

/** Event emitted when the selected value has been changed by the user. */
@Output() change: EventEmitter<MdSelectChange> = new EventEmitter<MdSelectChange>();

constructor(private _element: ElementRef, private _renderer: Renderer,
private _viewportRuler: ViewportRuler, @Optional() private _dir: Dir,
Expand Down Expand Up @@ -429,8 +437,8 @@ export class MdSelect implements AfterContentInit, ControlValueAccessor, OnDestr
private _listenToOptions(): void {
this.options.forEach((option: MdOption) => {
const sub = option.onSelect.subscribe((isUserInput: boolean) => {
if (isUserInput) {
this._onChange(option.value);
if (isUserInput && this._selected !== option) {
this._emitChangeEvent(option);
}
this._onSelect(option);
});
Expand All @@ -444,6 +452,12 @@ export class MdSelect implements AfterContentInit, ControlValueAccessor, OnDestr
this._subscriptions = [];
}

/** Emits an event when the user selects an option. */
private _emitChangeEvent(option: MdOption): void {
this._onChange(option.value);
this.change.emit(new MdSelectChange(this, option.value));
}

/** Records option IDs to pass to the aria-owns property. */
private _setOptionIds() {
this._optionIds = this.options.map(option => option.id).join(' ');
Expand Down