fix(select): support objects as select values

Closes #4843

Closes #7842
This commit is contained in:
Kara Erickson 2016-04-01 19:27:25 -07:00 committed by Kara
parent 52d3980d02
commit 74e2bd7e3e
4 changed files with 325 additions and 71 deletions

View File

@ -1,21 +1,78 @@
import { import {
Query,
Directive, Directive,
Renderer, Renderer,
Self,
forwardRef, forwardRef,
Provider, Provider,
ElementRef, ElementRef,
QueryList Input,
Host,
OnDestroy,
Optional
} from 'angular2/core'; } from 'angular2/core';
import {ObservableWrapper} from 'angular2/src/facade/async';
import {NG_VALUE_ACCESSOR, ControlValueAccessor} from './control_value_accessor'; import {NG_VALUE_ACCESSOR, ControlValueAccessor} from './control_value_accessor';
import {CONST_EXPR} from 'angular2/src/facade/lang'; import {
CONST_EXPR,
StringWrapper,
isPrimitive,
isPresent,
looseIdentical
} from 'angular2/src/facade/lang';
import {MapWrapper} from 'angular2/src/facade/collection';
const SELECT_VALUE_ACCESSOR = CONST_EXPR(new Provider( const SELECT_VALUE_ACCESSOR = CONST_EXPR(new Provider(
NG_VALUE_ACCESSOR, {useExisting: forwardRef(() => SelectControlValueAccessor), multi: true})); NG_VALUE_ACCESSOR, {useExisting: forwardRef(() => SelectControlValueAccessor), multi: true}));
function _buildValueString(id: string, value: any): string {
if (!isPrimitive(value)) value = "Object";
return StringWrapper.slice(`${id}: ${value}`, 0, 50);
}
function _extractId(valueString: string): string {
return valueString.split(":")[0];
}
/**
* The accessor for writing a value and listening to changes on a select element.
*/
@Directive({
selector: 'select[ngControl],select[ngFormControl],select[ngModel]',
host: {'(input)': 'onChange($event.target.value)', '(blur)': 'onTouched()'},
providers: [SELECT_VALUE_ACCESSOR]
})
export class SelectControlValueAccessor implements ControlValueAccessor {
value: any;
_optionMap: Map<string, any> = new Map<string, any>();
_idCounter: number = 0;
onChange = (_: any) => {};
onTouched = () => {};
constructor(private _renderer: Renderer, private _elementRef: ElementRef) {}
writeValue(value: any): void {
this.value = value;
var valueString = _buildValueString(this._getOptionId(value), value);
this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', valueString);
}
registerOnChange(fn: (value: any) => any): void {
this.onChange = (valueString: string) => { fn(this._getOptionValue(valueString)); };
}
registerOnTouched(fn: () => any): void { this.onTouched = fn; }
_registerOption(): string { return (this._idCounter++).toString(); }
_getOptionId(value: any): string {
for (let id of MapWrapper.keys(this._optionMap)) {
if (looseIdentical(this._optionMap.get(id), value)) return id;
}
return null;
}
_getOptionValue(valueString: string): any { return this._optionMap.get(_extractId(valueString)); }
}
/** /**
* Marks `<option>` as dynamic, so Angular can be notified when options change. * Marks `<option>` as dynamic, so Angular can be notified when options change.
* *
@ -28,36 +85,30 @@ const SELECT_VALUE_ACCESSOR = CONST_EXPR(new Provider(
* ``` * ```
*/ */
@Directive({selector: 'option'}) @Directive({selector: 'option'})
export class NgSelectOption { export class NgSelectOption implements OnDestroy {
} id: string;
/** constructor(private _element: ElementRef, private _renderer: Renderer,
* The accessor for writing a value and listening to changes on a select element. @Optional() @Host() private _select: SelectControlValueAccessor) {
*/ if (isPresent(this._select)) this.id = this._select._registerOption();
@Directive({
selector: 'select[ngControl],select[ngFormControl],select[ngModel]',
host: {'(input)': 'onChange($event.target.value)', '(blur)': 'onTouched()'},
bindings: [SELECT_VALUE_ACCESSOR]
})
export class SelectControlValueAccessor implements ControlValueAccessor {
value: string;
onChange = (_: any) => {};
onTouched = () => {};
constructor(private _renderer: Renderer, private _elementRef: ElementRef,
@Query(NgSelectOption, {descendants: true}) query: QueryList<NgSelectOption>) {
this._updateValueWhenListOfOptionsChanges(query);
} }
writeValue(value: any): void { @Input()
this.value = value; set value(value: any) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', value); if (this._select == null) return;
this._select._optionMap.set(this.id, value);
this._setElementValue(_buildValueString(this.id, value));
this._select.writeValue(this._select.value);
} }
registerOnChange(fn: () => any): void { this.onChange = fn; } _setElementValue(value: string): void {
registerOnTouched(fn: () => any): void { this.onTouched = fn; } this._renderer.setElementProperty(this._element.nativeElement, 'value', value);
}
private _updateValueWhenListOfOptionsChanges(query: QueryList<NgSelectOption>) { ngOnDestroy() {
ObservableWrapper.subscribe(query.changes, (_) => this.writeValue(this.value)); if (isPresent(this._select)) {
this._select._optionMap.delete(this.id);
this._select.writeValue(this._select.value);
}
} }
} }

View File

@ -94,14 +94,14 @@ export function main() {
}); });
it("should return select accessor when provided", () => { it("should return select accessor when provided", () => {
var selectAccessor = new SelectControlValueAccessor(null, null, new QueryList<any>()); var selectAccessor = new SelectControlValueAccessor(null, null);
expect(selectValueAccessor(dir, [defaultAccessor, selectAccessor])) expect(selectValueAccessor(dir, [defaultAccessor, selectAccessor]))
.toEqual(selectAccessor); .toEqual(selectAccessor);
}); });
it("should throw when more than one build-in accessor is provided", () => { it("should throw when more than one build-in accessor is provided", () => {
var checkboxAccessor = new CheckboxControlValueAccessor(null, null); var checkboxAccessor = new CheckboxControlValueAccessor(null, null);
var selectAccessor = new SelectControlValueAccessor(null, null, new QueryList<any>()); var selectAccessor = new SelectControlValueAccessor(null, null);
expect(() => selectValueAccessor(dir, [checkboxAccessor, selectAccessor])).toThrowError(); expect(() => selectValueAccessor(dir, [checkboxAccessor, selectAccessor])).toThrowError();
}); });

View File

@ -38,7 +38,7 @@ import {
import {Provider, forwardRef, Input} from 'angular2/core'; import {Provider, forwardRef, Input} from 'angular2/core';
import {By} from 'angular2/platform/browser'; import {By} from 'angular2/platform/browser';
import {ListWrapper} from 'angular2/src/facade/collection'; import {ListWrapper} from 'angular2/src/facade/collection';
import {ObservableWrapper} from 'angular2/src/facade/async'; import {ObservableWrapper, TimerWrapper} from 'angular2/src/facade/async';
import {CONST_EXPR} from 'angular2/src/facade/lang'; import {CONST_EXPR} from 'angular2/src/facade/lang';
import {PromiseWrapper} from "angular2/src/facade/promise"; import {PromiseWrapper} from "angular2/src/facade/promise";
@ -357,56 +357,253 @@ export function main() {
}); });
})); }));
it("should support <select>", describe("should support <select>", () => {
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { it("with basic selection",
var t = `<div [ngFormModel]="form"> inject([TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async) => {
var t = `<select>
<option value="SF"></option>
<option value="NYC"></option>
</select>`;
tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => {
fixture.detectChanges();
var select = fixture.debugElement.query(By.css("select"));
var sfOption = fixture.debugElement.query(By.css("option"));
expect(select.nativeElement.value).toEqual("SF");
expect(sfOption.nativeElement.selected).toBe(true);
async.done();
});
}));
it("with ngControl",
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder,
async) => {
var t = `<div [ngFormModel]="form">
<select ngControl="city"> <select ngControl="city">
<option value="SF"></option> <option value="SF"></option>
<option value="NYC"></option> <option value="NYC"></option>
</select> </select>
</div>`; </div>`;
tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => { tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => {
fixture.debugElement.componentInstance.form = fixture.debugElement.componentInstance.form =
new ControlGroup({"city": new Control("SF")}); new ControlGroup({"city": new Control("SF")});
fixture.detectChanges(); fixture.detectChanges();
var select = fixture.debugElement.query(By.css("select")); var select = fixture.debugElement.query(By.css("select"));
var sfOption = fixture.debugElement.query(By.css("option")); var sfOption = fixture.debugElement.query(By.css("option"));
expect(select.nativeElement.value).toEqual('SF');
expect(sfOption.nativeElement.selected).toBe(true);
select.nativeElement.value = 'NYC'; expect(select.nativeElement.value).toEqual("0: SF");
dispatchEvent(select.nativeElement, "input"); expect(sfOption.nativeElement.selected).toBe(true);
expect(fixture.debugElement.componentInstance.form.value).toEqual({"city": 'NYC'}); select.nativeElement.value = "1: NYC";
expect(sfOption.nativeElement.selected).toBe(false); dispatchEvent(select.nativeElement, "input");
async.done();
});
}));
it("should support <select> with a dynamic list of options", expect(fixture.debugElement.componentInstance.form.value).toEqual({"city": 'NYC'});
inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => { expect(sfOption.nativeElement.selected).toBe(false);
var t = `<div [ngFormModel]="form"> async.done();
});
}));
it("with a dynamic list of options",
inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => {
var t = `<div [ngFormModel]="form">
<select ngControl="city"> <select ngControl="city">
<option *ngFor="#c of data" [value]="c"></option> <option *ngFor="#c of data" [value]="c"></option>
</select> </select>
</div>`; </div>`;
var fixture; var fixture;
tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then( tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then(
(compFixture) => fixture = compFixture); (compFixture) => fixture = compFixture);
tick(); tick();
fixture.debugElement.componentInstance.form = fixture.debugElement.componentInstance.form =
new ControlGroup({"city": new Control("NYC")}); new ControlGroup({"city": new Control("NYC")});
fixture.debugElement.componentInstance.data = ['SF', 'NYC']; fixture.debugElement.componentInstance.data = ['SF', 'NYC'];
fixture.detectChanges(); fixture.detectChanges();
tick(); tick();
var select = fixture.debugElement.query(By.css('select')); var select = fixture.debugElement.query(By.css("select"));
expect(select.nativeElement.value).toEqual('NYC'); expect(select.nativeElement.value).toEqual("1: NYC");
}))); })));
it("with option values that are objects",
inject([TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async) => {
var t = `<div>
<select [(ngModel)]="selectedCity">
<option *ngFor="#c of list" [value]="c">{{c['name']}}</option>
</select>
</div>`;
tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => {
var testComp = fixture.debugElement.componentInstance;
testComp.list = [{"name": "SF"}, {"name": "NYC"}, {"name": "Buffalo"}];
testComp.selectedCity = testComp.list[1];
fixture.detectChanges();
var select = fixture.debugElement.query(By.css("select"));
var nycOption = fixture.debugElement.queryAll(By.css("option"))[1];
expect(select.nativeElement.value).toEqual("1: Object");
expect(nycOption.nativeElement.selected).toBe(true);
select.nativeElement.value = "2: Object";
dispatchEvent(select.nativeElement, "input");
fixture.detectChanges();
TimerWrapper.setTimeout(() => {
expect(testComp.selectedCity['name']).toEqual("Buffalo");
async.done();
}, 0);
});
}));
it("when new options are added",
inject([TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async) => {
var t = `<div>
<select [(ngModel)]="selectedCity">
<option *ngFor="#c of list" [value]="c">{{c['name']}}</option>
</select>
</div>`;
tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => {
var testComp: MyComp = fixture.debugElement.componentInstance;
testComp.list = [{"name": "SF"}, {"name": "NYC"}];
testComp.selectedCity = testComp.list[1];
fixture.detectChanges();
testComp.list.push({"name": "Buffalo"});
testComp.selectedCity = testComp.list[2];
fixture.detectChanges();
var select = fixture.debugElement.query(By.css("select"));
var buffalo = fixture.debugElement.queryAll(By.css("option"))[2];
expect(select.nativeElement.value).toEqual("2: Object");
expect(buffalo.nativeElement.selected).toBe(true);
async.done();
});
}));
it("when options are removed",
inject([TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async) => {
var t = `<div>
<select [(ngModel)]="selectedCity">
<option *ngFor="#c of list" [value]="c">{{c}}</option>
</select>
</div>`;
tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => {
var testComp: MyComp = fixture.debugElement.componentInstance;
testComp.list = ["SF", "NYC"];
testComp.selectedCity = testComp.list[1];
fixture.detectChanges();
var select = fixture.debugElement.query(By.css("select"));
expect(select.nativeElement.value).toEqual("1: NYC");
testComp.list.pop();
fixture.detectChanges();
expect(select.nativeElement.value).not.toEqual("1: NYC");
async.done();
});
}));
it("when option values change identity while tracking by index",
inject([TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async) => {
var t = `<div>
<select [(ngModel)]="selectedCity">
<option *ngFor="#c of list; trackBy:customTrackBy" [value]="c">{{c}}</option>
</select>
</div>`;
tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => {
var testComp = fixture.debugElement.componentInstance;
testComp.list = ["SF", "NYC"];
testComp.selectedCity = testComp.list[0];
fixture.detectChanges();
testComp.list[1] = "Buffalo";
testComp.selectedCity = "Buffalo";
fixture.detectChanges();
var select = fixture.debugElement.query(By.css("select"));
var buffalo = fixture.debugElement.queryAll(By.css("option"))[1];
expect(select.nativeElement.value).toEqual("1: Buffalo");
expect(buffalo.nativeElement.selected).toBe(true);
async.done();
});
}));
it("with duplicate option values",
inject([TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async) => {
var t = `<div>
<select [(ngModel)]="selectedCity">
<option *ngFor="#c of list" [value]="c">{{c}}</option>
</select>
</div>`;
tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => {
var testComp = fixture.debugElement.componentInstance;
testComp.list = ["NYC", "SF", "SF"];
testComp.selectedCity = testComp.list[0];
fixture.detectChanges();
testComp.selectedCity = "SF";
fixture.detectChanges();
var select = fixture.debugElement.query(By.css("select"));
var firstSF = fixture.debugElement.queryAll(By.css("option"))[1];
expect(select.nativeElement.value).toEqual("1: SF");
expect(firstSF.nativeElement.selected).toBe(true);
async.done();
});
}));
it("when option values have same content, but different identities",
inject([TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async) => {
var t = `<div>
<select [(ngModel)]="selectedCity">
<option *ngFor="#c of list" [value]="c">{{c['name']}}</option>
</select>
</div>`;
tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => {
var testComp = fixture.debugElement.componentInstance;
testComp.list = [{"name": "SF"}, {"name": "NYC"}, {"name": "NYC"}];
testComp.selectedCity = testComp.list[0];
fixture.detectChanges();
testComp.selectedCity = testComp.list[2];
fixture.detectChanges();
var select = fixture.debugElement.query(By.css("select"));
var secondNYC = fixture.debugElement.queryAll(By.css("option"))[2];
expect(select.nativeElement.value).toEqual("2: Object");
expect(secondNYC.nativeElement.selected).toBe(true);
async.done();
});
}));
});
it("should support custom value accessors", it("should support custom value accessors",
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => { inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
@ -849,7 +1046,6 @@ export function main() {
<input type="radio" name="food" ngControl="chicken" [(ngModel)]="data['chicken1']"> <input type="radio" name="food" ngControl="chicken" [(ngModel)]="data['chicken1']">
<input type="radio" name="food" ngControl="fish" [(ngModel)]="data['fish1']"> <input type="radio" name="food" ngControl="fish" [(ngModel)]="data['fish1']">
</form> </form>
<form> <form>
<input type="radio" name="food" ngControl="chicken" [(ngModel)]="data['chicken2']"> <input type="radio" name="food" ngControl="chicken" [(ngModel)]="data['chicken2']">
<input type="radio" name="food" ngControl="fish" [(ngModel)]="data['fish2']"> <input type="radio" name="food" ngControl="fish" [(ngModel)]="data['fish2']">
@ -1134,6 +1330,9 @@ class MyComp {
form: any; form: any;
name: string; name: string;
data: any; data: any;
list: any[];
selectedCity: any;
customTrackBy(index: number, obj: any): number { return index; };
} }
function sortedClassList(el) { function sortedClassList(el) {

View File

@ -777,6 +777,10 @@ const COMMON = [
'NgPlural.ngPlural=(value:number)', 'NgPlural.ngPlural=(value:number)',
'NgPluralCase', 'NgPluralCase',
'NgSelectOption', 'NgSelectOption',
'NgSelectOption.constructor(_element:ElementRef, _renderer:Renderer, _select:SelectControlValueAccessor)',
'NgSelectOption.id:string',
'NgSelectOption.ngOnDestroy():any',
'NgSelectOption.value=(value:any)',
'NgStyle', 'NgStyle',
'NgStyle.constructor(_differs:KeyValueDiffers, _ngEl:ElementRef, _renderer:Renderer)', 'NgStyle.constructor(_differs:KeyValueDiffers, _ngEl:ElementRef, _renderer:Renderer)',
'NgStyle.ngDoCheck():any', 'NgStyle.ngDoCheck():any',
@ -798,12 +802,12 @@ const COMMON = [
'ReplacePipe.transform(value:any, args:any[]):any', 'ReplacePipe.transform(value:any, args:any[]):any',
'RequiredValidator', 'RequiredValidator',
'SelectControlValueAccessor', 'SelectControlValueAccessor',
'SelectControlValueAccessor.constructor(_renderer:Renderer, _elementRef:ElementRef, query:QueryList<NgSelectOption>)', 'SelectControlValueAccessor.constructor(_renderer:Renderer, _elementRef:ElementRef)',
'SelectControlValueAccessor.onChange:any', 'SelectControlValueAccessor.onChange:any',
'SelectControlValueAccessor.onTouched:any', 'SelectControlValueAccessor.onTouched:any',
'SelectControlValueAccessor.registerOnChange(fn:() => any):void', 'SelectControlValueAccessor.registerOnChange(fn:(value: any) => any):void',
'SelectControlValueAccessor.registerOnTouched(fn:() => any):void', 'SelectControlValueAccessor.registerOnTouched(fn:() => any):void',
'SelectControlValueAccessor.value:string', 'SelectControlValueAccessor.value:any',
'SelectControlValueAccessor.writeValue(value:any):void', 'SelectControlValueAccessor.writeValue(value:any):void',
'SlicePipe', 'SlicePipe',
'SlicePipe.transform(value:any, args:any[]):any', 'SlicePipe.transform(value:any, args:any[]):any',