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 {
Query,
Directive,
Renderer,
Self,
forwardRef,
Provider,
ElementRef,
QueryList
Input,
Host,
OnDestroy,
Optional
} from 'angular2/core';
import {ObservableWrapper} from 'angular2/src/facade/async';
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(
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.
*
@ -28,36 +85,30 @@ const SELECT_VALUE_ACCESSOR = CONST_EXPR(new Provider(
* ```
*/
@Directive({selector: 'option'})
export class NgSelectOption {
}
export class NgSelectOption implements OnDestroy {
id: string;
/**
* 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()'},
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);
constructor(private _element: ElementRef, private _renderer: Renderer,
@Optional() @Host() private _select: SelectControlValueAccessor) {
if (isPresent(this._select)) this.id = this._select._registerOption();
}
writeValue(value: any): void {
this.value = value;
this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', value);
@Input()
set value(value: any) {
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; }
registerOnTouched(fn: () => any): void { this.onTouched = fn; }
_setElementValue(value: string): void {
this._renderer.setElementProperty(this._element.nativeElement, 'value', value);
}
private _updateValueWhenListOfOptionsChanges(query: QueryList<NgSelectOption>) {
ObservableWrapper.subscribe(query.changes, (_) => this.writeValue(this.value));
ngOnDestroy() {
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", () => {
var selectAccessor = new SelectControlValueAccessor(null, null, new QueryList<any>());
var selectAccessor = new SelectControlValueAccessor(null, null);
expect(selectValueAccessor(dir, [defaultAccessor, selectAccessor]))
.toEqual(selectAccessor);
});
it("should throw when more than one build-in accessor is provided", () => {
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();
});

View File

@ -38,7 +38,7 @@ import {
import {Provider, forwardRef, Input} from 'angular2/core';
import {By} from 'angular2/platform/browser';
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 {PromiseWrapper} from "angular2/src/facade/promise";
@ -357,56 +357,253 @@ export function main() {
});
}));
it("should support <select>",
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
var t = `<div [ngFormModel]="form">
describe("should support <select>", () => {
it("with basic selection",
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">
<option value="SF"></option>
<option value="NYC"></option>
</select>
</div>`;
tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => {
fixture.debugElement.componentInstance.form =
new ControlGroup({"city": new Control("SF")});
fixture.detectChanges();
tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then((fixture) => {
fixture.debugElement.componentInstance.form =
new ControlGroup({"city": new Control("SF")});
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);
var select = fixture.debugElement.query(By.css("select"));
var sfOption = fixture.debugElement.query(By.css("option"));
select.nativeElement.value = 'NYC';
dispatchEvent(select.nativeElement, "input");
expect(select.nativeElement.value).toEqual("0: SF");
expect(sfOption.nativeElement.selected).toBe(true);
expect(fixture.debugElement.componentInstance.form.value).toEqual({"city": 'NYC'});
expect(sfOption.nativeElement.selected).toBe(false);
async.done();
});
}));
select.nativeElement.value = "1: NYC";
dispatchEvent(select.nativeElement, "input");
it("should support <select> with a dynamic list of options",
inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => {
var t = `<div [ngFormModel]="form">
expect(fixture.debugElement.componentInstance.form.value).toEqual({"city": 'NYC'});
expect(sfOption.nativeElement.selected).toBe(false);
async.done();
});
}));
it("with a dynamic list of options",
inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => {
var t = `<div [ngFormModel]="form">
<select ngControl="city">
<option *ngFor="#c of data" [value]="c"></option>
</select>
</div>`;
var fixture;
tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then(
(compFixture) => fixture = compFixture);
tick();
var fixture;
tcb.overrideTemplate(MyComp, t).createAsync(MyComp).then(
(compFixture) => fixture = compFixture);
tick();
fixture.debugElement.componentInstance.form =
new ControlGroup({"city": new Control("NYC")});
fixture.debugElement.componentInstance.data = ['SF', 'NYC'];
fixture.detectChanges();
tick();
fixture.debugElement.componentInstance.form =
new ControlGroup({"city": new Control("NYC")});
fixture.debugElement.componentInstance.data = ['SF', 'NYC'];
fixture.detectChanges();
tick();
var select = fixture.debugElement.query(By.css('select'));
expect(select.nativeElement.value).toEqual('NYC');
})));
var select = fixture.debugElement.query(By.css("select"));
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",
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="fish" [(ngModel)]="data['fish1']">
</form>
<form>
<input type="radio" name="food" ngControl="chicken" [(ngModel)]="data['chicken2']">
<input type="radio" name="food" ngControl="fish" [(ngModel)]="data['fish2']">
@ -1134,6 +1330,9 @@ class MyComp {
form: any;
name: string;
data: any;
list: any[];
selectedCity: any;
customTrackBy(index: number, obj: any): number { return index; };
}
function sortedClassList(el) {

View File

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