feat(forms): allow both patching and strict setting of values (#10537)

This commit is contained in:
Kara 2016-08-05 13:35:17 -07:00 committed by Alex Rickabaugh
parent c586656d43
commit fcafdff10b
10 changed files with 503 additions and 145 deletions

View File

@ -127,7 +127,7 @@ export class NgForm extends ControlContainer implements Form {
}); });
} }
getControl(dir: NgModel): FormControl { return <FormControl>this.form.find(dir.path); } getControl(dir: NgModel): FormControl { return <FormControl>this.form.get(dir.path); }
removeControl(dir: NgModel): void { removeControl(dir: NgModel): void {
resolvedPromise.then(() => { resolvedPromise.then(() => {
@ -157,16 +157,16 @@ export class NgForm extends ControlContainer implements Form {
}); });
} }
getFormGroup(dir: NgModelGroup): FormGroup { return <FormGroup>this.form.find(dir.path); } getFormGroup(dir: NgModelGroup): FormGroup { return <FormGroup>this.form.get(dir.path); }
updateModel(dir: NgControl, value: any): void { updateModel(dir: NgControl, value: any): void {
resolvedPromise.then(() => { resolvedPromise.then(() => {
var ctrl = <FormControl>this.form.find(dir.path); var ctrl = <FormControl>this.form.get(dir.path);
ctrl.updateValue(value); ctrl.setValue(value);
}); });
} }
updateValue(value: {[key: string]: any}): void { this.control.updateValue(value); } setValue(value: {[key: string]: any}): void { this.control.setValue(value); }
onSubmit(): boolean { onSubmit(): boolean {
this._submitted = true; this._submitted = true;
@ -179,6 +179,6 @@ export class NgForm extends ControlContainer implements Form {
/** @internal */ /** @internal */
_findContainer(path: string[]): FormGroup { _findContainer(path: string[]): FormGroup {
path.pop(); path.pop();
return ListWrapper.isEmpty(path) ? this.form : <FormGroup>this.form.find(path); return ListWrapper.isEmpty(path) ? this.form : <FormGroup>this.form.get(path);
} }
} }

View File

@ -152,6 +152,6 @@ export class NgModel extends NgControl implements OnChanges,
private _updateValue(value: any): void { private _updateValue(value: any): void {
resolvedPromise.then( resolvedPromise.then(
() => { this.control.updateValue(value, {emitViewToModelChange: false}); }); () => { this.control.setValue(value, {emitViewToModelChange: false}); });
} }
} }

View File

@ -93,7 +93,7 @@ export class FormControlDirective extends NgControl implements OnChanges {
this.form.updateValueAndValidity({emitEvent: false}); this.form.updateValueAndValidity({emitEvent: false});
} }
if (isPropertyUpdated(changes, this.viewModel)) { if (isPropertyUpdated(changes, this.viewModel)) {
this.form.updateValue(this.model); this.form.setValue(this.model);
this.viewModel = this.model; this.viewModel = this.model;
} }
} }

View File

@ -145,39 +145,39 @@ export class FormGroupDirective extends ControlContainer implements Form,
get path(): string[] { return []; } get path(): string[] { return []; }
addControl(dir: NgControl): void { addControl(dir: NgControl): void {
const ctrl: any = this.form.find(dir.path); const ctrl: any = this.form.get(dir.path);
setUpControl(ctrl, dir); setUpControl(ctrl, dir);
ctrl.updateValueAndValidity({emitEvent: false}); ctrl.updateValueAndValidity({emitEvent: false});
this.directives.push(dir); this.directives.push(dir);
} }
getControl(dir: NgControl): FormControl { return <FormControl>this.form.find(dir.path); } getControl(dir: NgControl): FormControl { return <FormControl>this.form.get(dir.path); }
removeControl(dir: NgControl): void { ListWrapper.remove(this.directives, dir); } removeControl(dir: NgControl): void { ListWrapper.remove(this.directives, dir); }
addFormGroup(dir: FormGroupName): void { addFormGroup(dir: FormGroupName): void {
var ctrl: any = this.form.find(dir.path); var ctrl: any = this.form.get(dir.path);
setUpFormContainer(ctrl, dir); setUpFormContainer(ctrl, dir);
ctrl.updateValueAndValidity({emitEvent: false}); ctrl.updateValueAndValidity({emitEvent: false});
} }
removeFormGroup(dir: FormGroupName): void {} removeFormGroup(dir: FormGroupName): void {}
getFormGroup(dir: FormGroupName): FormGroup { return <FormGroup>this.form.find(dir.path); } getFormGroup(dir: FormGroupName): FormGroup { return <FormGroup>this.form.get(dir.path); }
addFormArray(dir: FormArrayName): void { addFormArray(dir: FormArrayName): void {
var ctrl: any = this.form.find(dir.path); var ctrl: any = this.form.get(dir.path);
setUpFormContainer(ctrl, dir); setUpFormContainer(ctrl, dir);
ctrl.updateValueAndValidity({emitEvent: false}); ctrl.updateValueAndValidity({emitEvent: false});
} }
removeFormArray(dir: FormArrayName): void {} removeFormArray(dir: FormArrayName): void {}
getFormArray(dir: FormArrayName): FormArray { return <FormArray>this.form.find(dir.path); } getFormArray(dir: FormArrayName): FormArray { return <FormArray>this.form.get(dir.path); }
updateModel(dir: NgControl, value: any): void { updateModel(dir: NgControl, value: any): void {
var ctrl  = <FormControl>this.form.find(dir.path); var ctrl  = <FormControl>this.form.get(dir.path);
ctrl.updateValue(value); ctrl.setValue(value);
} }
onSubmit(): boolean { onSubmit(): boolean {
@ -191,7 +191,7 @@ export class FormGroupDirective extends ControlContainer implements Form,
/** @internal */ /** @internal */
_updateDomValue() { _updateDomValue() {
this.directives.forEach(dir => { this.directives.forEach(dir => {
var ctrl: any = this.form.find(dir.path); var ctrl: any = this.form.get(dir.path);
dir.valueAccessor.writeValue(ctrl.value); dir.valueAccessor.writeValue(ctrl.value);
}); });
} }

View File

@ -46,7 +46,7 @@ export function setUpControl(control: FormControl, dir: NgControl): void {
dir.valueAccessor.registerOnChange((newValue: any) => { dir.valueAccessor.registerOnChange((newValue: any) => {
dir.viewToModelUpdate(newValue); dir.viewToModelUpdate(newValue);
control.markAsDirty(); control.markAsDirty();
control.updateValue(newValue, {emitModelToViewChange: false}); control.setValue(newValue, {emitModelToViewChange: false});
}); });
control.registerOnChange((newValue: any, emitModelEvent: boolean) => { control.registerOnChange((newValue: any, emitModelEvent: boolean) => {

View File

@ -177,7 +177,9 @@ export abstract class AbstractControl {
setParent(parent: FormGroup|FormArray): void { this._parent = parent; } setParent(parent: FormGroup|FormArray): void { this._parent = parent; }
abstract updateValue(value: any, options?: Object): void; abstract setValue(value: any, options?: Object): void;
abstract patchValue(value: any, options?: Object): void;
abstract reset(value?: any, options?: Object): void; abstract reset(value?: any, options?: Object): void;
@ -401,7 +403,7 @@ export class FormControl extends AbstractControl {
* If `emitViewToModelChange` is `true`, an ngModelChange event will be fired to update the * If `emitViewToModelChange` is `true`, an ngModelChange event will be fired to update the
* model. This is the default behavior if `emitViewToModelChange` is not specified. * model. This is the default behavior if `emitViewToModelChange` is not specified.
*/ */
updateValue(value: any, {onlySelf, emitEvent, emitModelToViewChange, emitViewToModelChange}: { setValue(value: any, {onlySelf, emitEvent, emitModelToViewChange, emitViewToModelChange}: {
onlySelf?: boolean, onlySelf?: boolean,
emitEvent?: boolean, emitEvent?: boolean,
emitModelToViewChange?: boolean, emitModelToViewChange?: boolean,
@ -417,10 +419,35 @@ export class FormControl extends AbstractControl {
this.updateValueAndValidity({onlySelf: onlySelf, emitEvent: emitEvent}); this.updateValueAndValidity({onlySelf: onlySelf, emitEvent: emitEvent});
} }
/**
* This function is functionally the same as updateValue() at this level. It exists for
* symmetry with patchValue() on FormGroups and FormArrays, where it does behave differently.
*/
patchValue(value: any, options: {
onlySelf?: boolean,
emitEvent?: boolean,
emitModelToViewChange?: boolean,
emitViewToModelChange?: boolean
} = {}): void {
this.setValue(value, options);
}
/**
* @deprecated Please use setValue() instead.
*/
updateValue(value: any, options: {
onlySelf?: boolean,
emitEvent?: boolean,
emitModelToViewChange?: boolean,
emitViewToModelChange?: boolean
} = {}): void {
this.setValue(value, options);
}
reset(value: any = null, {onlySelf}: {onlySelf?: boolean} = {}): void { reset(value: any = null, {onlySelf}: {onlySelf?: boolean} = {}): void {
this.markAsPristine({onlySelf: onlySelf}); this.markAsPristine({onlySelf: onlySelf});
this.markAsUntouched({onlySelf: onlySelf}); this.markAsUntouched({onlySelf: onlySelf});
this.updateValue(value, {onlySelf: onlySelf}); this.setValue(value, {onlySelf: onlySelf});
} }
/** /**
@ -523,10 +550,20 @@ export class FormGroup extends AbstractControl {
return c && this._included(controlName); return c && this._included(controlName);
} }
updateValue(value: {[key: string]: any}, {onlySelf}: {onlySelf?: boolean} = {}): void { setValue(value: {[key: string]: any}, {onlySelf}: {onlySelf?: boolean} = {}): void {
this._checkAllValuesPresent(value);
StringMapWrapper.forEach(value, (newValue: any, name: string) => { StringMapWrapper.forEach(value, (newValue: any, name: string) => {
this._throwIfControlMissing(name); this._throwIfControlMissing(name);
this.controls[name].updateValue(newValue, {onlySelf: true}); this.controls[name].setValue(newValue, {onlySelf: true});
});
this.updateValueAndValidity({onlySelf: onlySelf});
}
patchValue(value: {[key: string]: any}, {onlySelf}: {onlySelf?: boolean} = {}): void {
StringMapWrapper.forEach(value, (newValue: any, name: string) => {
if (this.controls[name]) {
this.controls[name].patchValue(newValue, {onlySelf: true});
}
}); });
this.updateValueAndValidity({onlySelf: onlySelf}); this.updateValueAndValidity({onlySelf: onlySelf});
} }
@ -542,6 +579,12 @@ export class FormGroup extends AbstractControl {
/** @internal */ /** @internal */
_throwIfControlMissing(name: string): void { _throwIfControlMissing(name: string): void {
if (!Object.keys(this.controls).length) {
throw new BaseException(`
There are no form controls registered with this group yet. If you're using ngModel,
you may want to check next tick (e.g. use setTimeout).
`);
}
if (!this.controls[name]) { if (!this.controls[name]) {
throw new BaseException(`Cannot find form control with name: ${name}.`); throw new BaseException(`Cannot find form control with name: ${name}.`);
} }
@ -594,6 +637,15 @@ export class FormGroup extends AbstractControl {
var isOptional = StringMapWrapper.contains(this._optionals, controlName); var isOptional = StringMapWrapper.contains(this._optionals, controlName);
return !isOptional || StringMapWrapper.get(this._optionals, controlName); return !isOptional || StringMapWrapper.get(this._optionals, controlName);
} }
/** @internal */
_checkAllValuesPresent(value: any): void {
this._forEachChild((control: AbstractControl, name: string) => {
if (value[name] === undefined) {
throw new BaseException(`Must supply a value for form control with name: '${name}'.`);
}
});
}
} }
/** /**
@ -666,10 +718,20 @@ export class FormArray extends AbstractControl {
*/ */
get length(): number { return this.controls.length; } get length(): number { return this.controls.length; }
updateValue(value: any[], {onlySelf}: {onlySelf?: boolean} = {}): void { setValue(value: any[], {onlySelf}: {onlySelf?: boolean} = {}): void {
this._checkAllValuesPresent(value);
value.forEach((newValue: any, index: number) => { value.forEach((newValue: any, index: number) => {
this._throwIfControlMissing(index); this._throwIfControlMissing(index);
this.at(index).updateValue(newValue, {onlySelf: true}); this.at(index).setValue(newValue, {onlySelf: true});
});
this.updateValueAndValidity({onlySelf: onlySelf});
}
patchValue(value: any[], {onlySelf}: {onlySelf?: boolean} = {}): void {
value.forEach((newValue: any, index: number) => {
if (this.at(index)) {
this.at(index).patchValue(newValue, {onlySelf: true});
}
}); });
this.updateValueAndValidity({onlySelf: onlySelf}); this.updateValueAndValidity({onlySelf: onlySelf});
} }
@ -685,6 +747,12 @@ export class FormArray extends AbstractControl {
/** @internal */ /** @internal */
_throwIfControlMissing(index: number): void { _throwIfControlMissing(index: number): void {
if (!this.controls.length) {
throw new BaseException(`
There are no form controls registered with this array yet. If you're using ngModel,
you may want to check next tick (e.g. use setTimeout).
`);
}
if (!this.at(index)) { if (!this.at(index)) {
throw new BaseException(`Cannot find form control at index ${index}`); throw new BaseException(`Cannot find form control at index ${index}`);
} }
@ -707,4 +775,13 @@ export class FormArray extends AbstractControl {
_setParentForControls(): void { _setParentForControls(): void {
this._forEachChild((control: AbstractControl) => { control.setParent(this); }); this._forEachChild((control: AbstractControl) => { control.setParent(this); });
} }
/** @internal */
_checkAllValuesPresent(value: any): void {
this._forEachChild((control: AbstractControl, i: number) => {
if (value[i] === undefined) {
throw new BaseException(`Must supply a value for form control at index: ${i}.`);
}
});
}
} }

View File

@ -193,7 +193,7 @@ export function main() {
expect(formModel.hasError('required', ['login'])).toBe(true); expect(formModel.hasError('required', ['login'])).toBe(true);
expect(formModel.hasError('async', ['login'])).toBe(false); expect(formModel.hasError('async', ['login'])).toBe(false);
(<FormControl>formModel.find(['login'])).updateValue('invalid value'); (<FormControl>formModel.get('login')).setValue('invalid value');
// sync validator passes, running async validators // sync validator passes, running async validators
expect(formModel.pending).toBe(true); expect(formModel.pending).toBe(true);
@ -205,7 +205,7 @@ export function main() {
})); }));
it('should write value to the DOM', () => { it('should write value to the DOM', () => {
(<FormControl>formModel.find(['login'])).updateValue('initValue'); (<FormControl>formModel.get(['login'])).setValue('initValue');
form.addControl(loginControlDir); form.addControl(loginControlDir);
@ -233,17 +233,17 @@ export function main() {
group.name = 'passwords'; group.name = 'passwords';
form.addFormGroup(group); form.addFormGroup(group);
(<FormControl>formModel.find(['passwords', 'password'])).updateValue('somePassword'); (<FormControl>formModel.get(['passwords', 'password'])).setValue('somePassword');
(<FormControl>formModel.find([ (<FormControl>formModel.get([
'passwords', 'passwordConfirm' 'passwords', 'passwordConfirm'
])).updateValue('someOtherPassword'); ])).setValue('someOtherPassword');
// sync validators are set // sync validators are set
expect(formModel.hasError('differentPasswords', ['passwords'])).toEqual(true); expect(formModel.hasError('differentPasswords', ['passwords'])).toEqual(true);
(<FormControl>formModel.find([ (<FormControl>formModel.get([
'passwords', 'passwordConfirm' 'passwords', 'passwordConfirm'
])).updateValue('somePassword'); ])).setValue('somePassword');
// sync validators pass, running async validators // sync validators pass, running async validators
expect(formModel.pending).toBe(true); expect(formModel.pending).toBe(true);
@ -266,7 +266,7 @@ export function main() {
it('should update dom values of all the directives', () => { it('should update dom values of all the directives', () => {
form.addControl(loginControlDir); form.addControl(loginControlDir);
(<FormControl>formModel.find(['login'])).updateValue('new value'); (<FormControl>formModel.get(['login'])).setValue('new value');
form.ngOnChanges({}); form.ngOnChanges({});
@ -334,7 +334,7 @@ export function main() {
flushMicrotasks(); flushMicrotasks();
expect(formModel.find(['person', 'login'])).not.toBeNull; expect(formModel.get(['person', 'login'])).not.toBeNull;
})); }));
// should update the form's value and validity // should update the form's value and validity
@ -350,8 +350,8 @@ export function main() {
flushMicrotasks(); flushMicrotasks();
expect(formModel.find(['person'])).toBeNull(); expect(formModel.get(['person'])).toBeNull();
expect(formModel.find(['person', 'login'])).toBeNull(); expect(formModel.get(['person', 'login'])).toBeNull();
})); }));
// should update the form's value and validity // should update the form's value and validity
@ -524,7 +524,7 @@ export function main() {
expect(ngModel.control.errors).toEqual({'required': true}); expect(ngModel.control.errors).toEqual({'required': true});
ngModel.control.updateValue('someValue'); ngModel.control.setValue('someValue');
tick(); tick();
expect(ngModel.control.errors).toEqual({'async': true}); expect(ngModel.control.errors).toEqual({'async': true});

View File

@ -56,16 +56,16 @@ export function main() {
it('should rerun the validator when the value changes', () => { it('should rerun the validator when the value changes', () => {
var c = new FormControl('value', Validators.required); var c = new FormControl('value', Validators.required);
c.updateValue(null); c.setValue(null);
expect(c.valid).toEqual(false); expect(c.valid).toEqual(false);
}); });
it('should support arrays of validator functions if passed', () => { it('should support arrays of validator functions if passed', () => {
const c = new FormControl('value', [Validators.required, Validators.minLength(3)]); const c = new FormControl('value', [Validators.required, Validators.minLength(3)]);
c.updateValue('a'); c.setValue('a');
expect(c.valid).toEqual(false); expect(c.valid).toEqual(false);
c.updateValue('aaa'); c.setValue('aaa');
expect(c.valid).toEqual(true); expect(c.valid).toEqual(true);
}); });
@ -80,10 +80,10 @@ export function main() {
c.setValidators(Validators.required); c.setValidators(Validators.required);
c.updateValue(null); c.setValue(null);
expect(c.valid).toEqual(false); expect(c.valid).toEqual(false);
c.updateValue('abc'); c.setValue('abc');
expect(c.valid).toEqual(true); expect(c.valid).toEqual(true);
}); });
@ -93,13 +93,13 @@ export function main() {
c.setValidators([Validators.minLength(5), Validators.required]); c.setValidators([Validators.minLength(5), Validators.required]);
c.updateValue(''); c.setValue('');
expect(c.valid).toEqual(false); expect(c.valid).toEqual(false);
c.updateValue('abc'); c.setValue('abc');
expect(c.valid).toEqual(false); expect(c.valid).toEqual(false);
c.updateValue('abcde'); c.setValue('abcde');
expect(c.valid).toEqual(true); expect(c.valid).toEqual(true);
}); });
@ -110,7 +110,7 @@ export function main() {
c.clearValidators(); c.clearValidators();
expect(c.validator).toEqual(null); expect(c.validator).toEqual(null);
c.updateValue(''); c.setValue('');
expect(c.valid).toEqual(true); expect(c.valid).toEqual(true);
}); });
@ -146,7 +146,7 @@ export function main() {
it('should rerun the validator when the value changes', fakeAsync(() => { it('should rerun the validator when the value changes', fakeAsync(() => {
var c = new FormControl('value', null, asyncValidator('expected')); var c = new FormControl('value', null, asyncValidator('expected'));
c.updateValue('expected'); c.setValue('expected');
tick(); tick();
expect(c.valid).toEqual(true); expect(c.valid).toEqual(true);
@ -158,7 +158,7 @@ export function main() {
expect(c.errors).toEqual({'required': true}); expect(c.errors).toEqual({'required': true});
c.updateValue('some value'); c.setValue('some value');
tick(); tick();
expect(c.errors).toEqual({'async': true}); expect(c.errors).toEqual({'async': true});
@ -179,8 +179,8 @@ export function main() {
var c = new FormControl( var c = new FormControl(
'', null, asyncValidator('expected', {'long': 200, 'expected': 100})); '', null, asyncValidator('expected', {'long': 200, 'expected': 100}));
c.updateValue('long'); c.setValue('long');
c.updateValue('expected'); c.setValue('expected');
tick(300); tick(300);
@ -201,7 +201,7 @@ export function main() {
c.setAsyncValidators(asyncValidator('expected')); c.setAsyncValidators(asyncValidator('expected'));
expect(c.asyncValidator).not.toEqual(null); expect(c.asyncValidator).not.toEqual(null);
c.updateValue('expected'); c.setValue('expected');
tick(); tick();
expect(c.valid).toEqual(true); expect(c.valid).toEqual(true);
@ -213,7 +213,7 @@ export function main() {
c.setAsyncValidators([asyncValidator('expected')]); c.setAsyncValidators([asyncValidator('expected')]);
expect(c.asyncValidator).not.toEqual(null); expect(c.asyncValidator).not.toEqual(null);
c.updateValue('expected'); c.setValue('expected');
tick(); tick();
expect(c.valid).toEqual(true); expect(c.valid).toEqual(true);
@ -254,6 +254,119 @@ export function main() {
}); });
}); });
describe('setValue', () => {
let g: FormGroup, c: FormControl;
beforeEach(() => {
c = new FormControl('oldValue');
g = new FormGroup({'one': c});
});
it('should set the value of the control', () => {
c.setValue('newValue');
expect(c.value).toEqual('newValue');
});
it('should invoke ngOnChanges if it is present', () => {
let ngOnChanges: any;
c.registerOnChange((v: any) => ngOnChanges = ['invoked', v]);
c.setValue('newValue');
expect(ngOnChanges).toEqual(['invoked', 'newValue']);
});
it('should not invoke on change when explicitly specified', () => {
let onChange: any = null;
c.registerOnChange((v: any) => onChange = ['invoked', v]);
c.setValue('newValue', {emitModelToViewChange: false});
expect(onChange).toBeNull();
});
it('should set the parent', () => {
c.setValue('newValue');
expect(g.value).toEqual({'one': 'newValue'});
});
it('should not set the parent when explicitly specified', () => {
c.setValue('newValue', {onlySelf: true});
expect(g.value).toEqual({'one': 'oldValue'});
});
it('should fire an event', fakeAsync(() => {
c.valueChanges.subscribe((value) => { expect(value).toEqual('newValue'); });
c.setValue('newValue');
tick();
}));
it('should not fire an event when explicitly specified', fakeAsync(() => {
c.valueChanges.subscribe((value) => { throw 'Should not happen'; });
c.setValue('newValue', {emitEvent: false});
tick();
}));
});
describe('patchValue', () => {
let g: FormGroup, c: FormControl;
beforeEach(() => {
c = new FormControl('oldValue');
g = new FormGroup({'one': c});
});
it('should set the value of the control', () => {
c.patchValue('newValue');
expect(c.value).toEqual('newValue');
});
it('should invoke ngOnChanges if it is present', () => {
let ngOnChanges: any;
c.registerOnChange((v: any) => ngOnChanges = ['invoked', v]);
c.patchValue('newValue');
expect(ngOnChanges).toEqual(['invoked', 'newValue']);
});
it('should not invoke on change when explicitly specified', () => {
let onChange: any = null;
c.registerOnChange((v: any) => onChange = ['invoked', v]);
c.patchValue('newValue', {emitModelToViewChange: false});
expect(onChange).toBeNull();
});
it('should set the parent', () => {
c.patchValue('newValue');
expect(g.value).toEqual({'one': 'newValue'});
});
it('should not set the parent when explicitly specified', () => {
c.patchValue('newValue', {onlySelf: true});
expect(g.value).toEqual({'one': 'oldValue'});
});
it('should fire an event', fakeAsync(() => {
c.valueChanges.subscribe((value) => { expect(value).toEqual('newValue'); });
c.patchValue('newValue');
tick();
}));
it('should not fire an event when explicitly specified', fakeAsync(() => {
c.valueChanges.subscribe((value) => { throw 'Should not happen'; });
c.patchValue('newValue', {emitEvent: false});
tick();
}));
});
// deprecated function
// TODO(kara): remove these tests when updateValue is removed
describe('updateValue', () => { describe('updateValue', () => {
var g: any /** TODO #9100 */, c: any /** TODO #9100 */; var g: any /** TODO #9100 */, c: any /** TODO #9100 */;
beforeEach(() => { beforeEach(() => {
@ -318,7 +431,7 @@ export function main() {
beforeEach(() => { c = new FormControl('initial value'); }); beforeEach(() => { c = new FormControl('initial value'); });
it('should restore the initial value of the control if passed', () => { it('should restore the initial value of the control if passed', () => {
c.updateValue('new value'); c.setValue('new value');
expect(c.value).toBe('new value'); expect(c.value).toBe('new value');
c.reset('initial value'); c.reset('initial value');
@ -326,7 +439,7 @@ export function main() {
}); });
it('should clear the control value if no value is passed', () => { it('should clear the control value if no value is passed', () => {
c.updateValue('new value'); c.setValue('new value');
expect(c.value).toBe('new value'); expect(c.value).toBe('new value');
c.reset(); c.reset();
@ -335,7 +448,7 @@ export function main() {
it('should update the value of any parent controls with passed value', () => { it('should update the value of any parent controls with passed value', () => {
const g = new FormGroup({'one': c}); const g = new FormGroup({'one': c});
c.updateValue('new value'); c.setValue('new value');
expect(g.value).toEqual({'one': 'new value'}); expect(g.value).toEqual({'one': 'new value'});
c.reset('initial value'); c.reset('initial value');
@ -344,7 +457,7 @@ export function main() {
it('should update the value of any parent controls with null value', () => { it('should update the value of any parent controls with null value', () => {
const g = new FormGroup({'one': c}); const g = new FormGroup({'one': c});
c.updateValue('new value'); c.setValue('new value');
expect(g.value).toEqual({'one': 'new value'}); expect(g.value).toEqual({'one': 'new value'});
c.reset(); c.reset();
@ -450,7 +563,7 @@ export function main() {
async.done(); async.done();
} }
}); });
c.updateValue('new'); c.setValue('new');
})); }));
it('should fire an event after the status has been updated to invalid', fakeAsync(() => { it('should fire an event after the status has been updated to invalid', fakeAsync(() => {
@ -461,7 +574,7 @@ export function main() {
} }
}); });
c.updateValue(''); c.setValue('');
tick(); tick();
})); }));
@ -473,13 +586,13 @@ export function main() {
c.statusChanges.subscribe({next: (status: any) => log.push(`status: '${status}'`)}); c.statusChanges.subscribe({next: (status: any) => log.push(`status: '${status}'`)});
c.updateValue(''); c.setValue('');
tick(); tick();
c.updateValue('nonEmpty'); c.setValue('nonEmpty');
tick(); tick();
c.updateValue('expected'); c.setValue('expected');
tick(); tick();
expect(log).toEqual([ expect(log).toEqual([
@ -503,19 +616,19 @@ export function main() {
expect(c.errors).toEqual({'required': true}); expect(c.errors).toEqual({'required': true});
async.done(); async.done();
}); });
c.updateValue(''); c.setValue('');
})); }));
it('should return a cold observable', it('should return a cold observable',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
c.updateValue('will be ignored'); c.setValue('will be ignored');
c.valueChanges.subscribe({ c.valueChanges.subscribe({
next: (value: any) => { next: (value: any) => {
expect(value).toEqual('new'); expect(value).toEqual('new');
async.done(); async.done();
} }
}); });
c.updateValue('new'); c.setValue('new');
})); }));
}); });
@ -533,7 +646,7 @@ export function main() {
var c = new FormControl('someValue', Validators.required); var c = new FormControl('someValue', Validators.required);
c.setErrors({'someError': true}); c.setErrors({'someError': true});
c.updateValue(''); c.setValue('');
expect(c.errors).toEqual({'required': true}); expect(c.errors).toEqual({'required': true});
}); });
@ -566,7 +679,7 @@ export function main() {
g.setErrors({'someGroupError': true}); g.setErrors({'someGroupError': true});
c.setErrors({'someError': true}); c.setErrors({'someError': true});
c.updateValue('newValue'); c.setValue('newValue');
expect(c.errors).toEqual(null); expect(c.errors).toEqual(null);
expect(g.errors).toEqual(null); expect(g.errors).toEqual(null);
@ -593,7 +706,7 @@ export function main() {
}); });
expect(g.value).toEqual({'one': '111', 'nested': {'two': '222'}}); expect(g.value).toEqual({'one': '111', 'nested': {'two': '222'}});
(<FormControl>(g.controls['nested'].find('two'))).updateValue('333'); (<FormControl>(g.get('nested.two'))).setValue('333');
expect(g.value).toEqual({'one': '111', 'nested': {'two': '333'}}); expect(g.value).toEqual({'one': '111', 'nested': {'two': '333'}});
}); });
@ -632,12 +745,12 @@ export function main() {
var c = new FormControl(null); var c = new FormControl(null);
var g = new FormGroup({'one': c}, null, simpleValidator); var g = new FormGroup({'one': c}, null, simpleValidator);
c.updateValue('correct'); c.setValue('correct');
expect(g.valid).toEqual(true); expect(g.valid).toEqual(true);
expect(g.errors).toEqual(null); expect(g.errors).toEqual(null);
c.updateValue('incorrect'); c.setValue('incorrect');
expect(g.valid).toEqual(false); expect(g.valid).toEqual(false);
expect(g.errors).toEqual({'broken': true}); expect(g.errors).toEqual({'broken': true});
@ -679,7 +792,7 @@ export function main() {
}); });
}); });
describe('updateValue', () => { describe('setValue', () => {
let c: FormControl, c2: FormControl, g: FormGroup; let c: FormControl, c2: FormControl, g: FormGroup;
beforeEach(() => { beforeEach(() => {
@ -688,40 +801,42 @@ export function main() {
g = new FormGroup({'one': c, 'two': c2}); g = new FormGroup({'one': c, 'two': c2});
}); });
it('should update its own value', () => { it('should set its own value', () => {
g.updateValue({'one': 'one', 'two': 'two'}); g.setValue({'one': 'one', 'two': 'two'});
expect(g.value).toEqual({'one': 'one', 'two': 'two'}); expect(g.value).toEqual({'one': 'one', 'two': 'two'});
}); });
it('should update child values', () => { it('should set child values', () => {
g.updateValue({'one': 'one', 'two': 'two'}); g.setValue({'one': 'one', 'two': 'two'});
expect(c.value).toEqual('one'); expect(c.value).toEqual('one');
expect(c2.value).toEqual('two'); expect(c2.value).toEqual('two');
}); });
it('should update parent values', () => { it('should set parent values', () => {
const form = new FormGroup({'parent': g}); const form = new FormGroup({'parent': g});
g.updateValue({'one': 'one', 'two': 'two'}); g.setValue({'one': 'one', 'two': 'two'});
expect(form.value).toEqual({'parent': {'one': 'one', 'two': 'two'}}); expect(form.value).toEqual({'parent': {'one': 'one', 'two': 'two'}});
}); });
it('should ignore fields that are missing from supplied value', () => { it('should throw if fields are missing from supplied value (subset)', () => {
g.updateValue({'one': 'one'}); expect(() => g.setValue({
expect(g.value).toEqual({'one': 'one', 'two': ''}); 'one': 'one'
})).toThrowError(new RegExp(`Must supply a value for form control with name: 'two'`));
}); });
it('should not ignore fields that are null', () => { it('should throw if a value is provided for a missing control (superset)', () => {
g.updateValue({'one': null}); expect(() => g.setValue({'one': 'one', 'two': 'two', 'three': 'three'}))
expect(g.value).toEqual({'one': null, 'two': ''}); .toThrowError(new RegExp(`Cannot find form control with name: three`));
}); });
it('should throw if a value is provided for a missing control', () => { it('should throw if no controls are set yet', () => {
expect(() => g.updateValue({ const empty = new FormGroup({});
'three': 'three' expect(() => empty.setValue({
})).toThrowError(new RegExp(`Cannot find form control with name: three`)); 'one': 'one'
})).toThrowError(new RegExp(`no form controls registered with this group`));
}); });
describe('updateValue() events', () => { describe('setValue() events', () => {
let form: FormGroup; let form: FormGroup;
let logger: any[]; let logger: any[];
@ -736,7 +851,79 @@ export function main() {
c.valueChanges.subscribe(() => logger.push('control1')); c.valueChanges.subscribe(() => logger.push('control1'));
c2.valueChanges.subscribe(() => logger.push('control2')); c2.valueChanges.subscribe(() => logger.push('control2'));
g.updateValue({'one': 'one', 'two': 'two'}); g.setValue({'one': 'one', 'two': 'two'});
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
it('should emit one statusChange event per control', () => {
form.statusChanges.subscribe(() => logger.push('form'));
g.statusChanges.subscribe(() => logger.push('group'));
c.statusChanges.subscribe(() => logger.push('control1'));
c2.statusChanges.subscribe(() => logger.push('control2'));
g.setValue({'one': 'one', 'two': 'two'});
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
});
});
describe('patchValue', () => {
let c: FormControl, c2: FormControl, g: FormGroup;
beforeEach(() => {
c = new FormControl('');
c2 = new FormControl('');
g = new FormGroup({'one': c, 'two': c2});
});
it('should set its own value', () => {
g.patchValue({'one': 'one', 'two': 'two'});
expect(g.value).toEqual({'one': 'one', 'two': 'two'});
});
it('should set child values', () => {
g.patchValue({'one': 'one', 'two': 'two'});
expect(c.value).toEqual('one');
expect(c2.value).toEqual('two');
});
it('should set parent values', () => {
const form = new FormGroup({'parent': g});
g.patchValue({'one': 'one', 'two': 'two'});
expect(form.value).toEqual({'parent': {'one': 'one', 'two': 'two'}});
});
it('should ignore fields that are missing from supplied value (subset)', () => {
g.patchValue({'one': 'one'});
expect(g.value).toEqual({'one': 'one', 'two': ''});
});
it('should not ignore fields that are null', () => {
g.patchValue({'one': null});
expect(g.value).toEqual({'one': null, 'two': ''});
});
it('should ignore any value provided for a missing control (superset)', () => {
g.patchValue({'three': 'three'});
expect(g.value).toEqual({'one': '', 'two': ''});
});
describe('patchValue() events', () => {
let form: FormGroup;
let logger: any[];
beforeEach(() => {
form = new FormGroup({'parent': g});
logger = [];
});
it('should emit one valueChange event per control', () => {
form.valueChanges.subscribe(() => logger.push('form'));
g.valueChanges.subscribe(() => logger.push('group'));
c.valueChanges.subscribe(() => logger.push('control1'));
c2.valueChanges.subscribe(() => logger.push('control2'));
g.patchValue({'one': 'one', 'two': 'two'});
expect(logger).toEqual(['control1', 'control2', 'group', 'form']); expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
}); });
@ -746,7 +933,7 @@ export function main() {
c.valueChanges.subscribe(() => logger.push('control1')); c.valueChanges.subscribe(() => logger.push('control1'));
c2.valueChanges.subscribe(() => logger.push('control2')); c2.valueChanges.subscribe(() => logger.push('control2'));
g.updateValue({'one': 'one'}); g.patchValue({'one': 'one'});
expect(logger).toEqual(['control1', 'group', 'form']); expect(logger).toEqual(['control1', 'group', 'form']);
}); });
@ -756,7 +943,7 @@ export function main() {
c.statusChanges.subscribe(() => logger.push('control1')); c.statusChanges.subscribe(() => logger.push('control1'));
c2.statusChanges.subscribe(() => logger.push('control2')); c2.statusChanges.subscribe(() => logger.push('control2'));
g.updateValue({'one': 'one', 'two': 'two'}); g.patchValue({'one': 'one', 'two': 'two'});
expect(logger).toEqual(['control1', 'control2', 'group', 'form']); expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
}); });
}); });
@ -772,21 +959,21 @@ export function main() {
}); });
it('should set its own value if value passed', () => { it('should set its own value if value passed', () => {
g.updateValue({'one': 'new value', 'two': 'new value'}); g.setValue({'one': 'new value', 'two': 'new value'});
g.reset({'one': 'initial value', 'two': ''}); g.reset({'one': 'initial value', 'two': ''});
expect(g.value).toEqual({'one': 'initial value', 'two': ''}); expect(g.value).toEqual({'one': 'initial value', 'two': ''});
}); });
it('should clear its own value if no value passed', () => { it('should clear its own value if no value passed', () => {
g.updateValue({'one': 'new value', 'two': 'new value'}); g.setValue({'one': 'new value', 'two': 'new value'});
g.reset(); g.reset();
expect(g.value).toEqual({'one': null, 'two': null}); expect(g.value).toEqual({'one': null, 'two': null});
}); });
it('should set the value of each of its child controls if value passed', () => { it('should set the value of each of its child controls if value passed', () => {
g.updateValue({'one': 'new value', 'two': 'new value'}); g.setValue({'one': 'new value', 'two': 'new value'});
g.reset({'one': 'initial value', 'two': ''}); g.reset({'one': 'initial value', 'two': ''});
expect(c.value).toBe('initial value'); expect(c.value).toBe('initial value');
@ -794,7 +981,7 @@ export function main() {
}); });
it('should clear the value of each of its child controls if no value passed', () => { it('should clear the value of each of its child controls if no value passed', () => {
g.updateValue({'one': 'new value', 'two': 'new value'}); g.setValue({'one': 'new value', 'two': 'new value'});
g.reset(); g.reset();
expect(c.value).toBe(null); expect(c.value).toBe(null);
@ -803,7 +990,7 @@ export function main() {
it('should set the value of its parent if value passed', () => { it('should set the value of its parent if value passed', () => {
const form = new FormGroup({'g': g}); const form = new FormGroup({'g': g});
g.updateValue({'one': 'new value', 'two': 'new value'}); g.setValue({'one': 'new value', 'two': 'new value'});
g.reset({'one': 'initial value', 'two': ''}); g.reset({'one': 'initial value', 'two': ''});
expect(form.value).toEqual({'g': {'one': 'initial value', 'two': ''}}); expect(form.value).toEqual({'g': {'one': 'initial value', 'two': ''}});
@ -811,7 +998,7 @@ export function main() {
it('should clear the value of its parent if no value passed', () => { it('should clear the value of its parent if no value passed', () => {
const form = new FormGroup({'g': g}); const form = new FormGroup({'g': g});
g.updateValue({'one': 'new value', 'two': 'new value'}); g.setValue({'one': 'new value', 'two': 'new value'});
g.reset(); g.reset();
expect(form.value).toEqual({'g': {'one': null, 'two': null}}); expect(form.value).toEqual({'g': {'one': null, 'two': null}});
@ -1013,7 +1200,7 @@ export function main() {
async.done(); async.done();
} }
}); });
c1.updateValue('new1'); c1.setValue('new1');
})); }));
it('should fire an event after the control\'s observable fired an event', it('should fire an event after the control\'s observable fired an event',
@ -1030,7 +1217,7 @@ export function main() {
} }
}); });
c1.updateValue('new1'); c1.setValue('new1');
})); }));
it('should fire an event when a control is excluded', it('should fire an event when a control is excluded',
@ -1076,8 +1263,8 @@ export function main() {
} }
}); });
c1.updateValue('new1'); c1.setValue('new1');
c2.updateValue('new2'); c2.setValue('new2');
})); }));
// hard to test without hacking zones // hard to test without hacking zones
@ -1101,7 +1288,7 @@ export function main() {
async.done(); async.done();
} }
}); });
control.updateValue(''); control.setValue('');
})); }));
}); });
@ -1154,7 +1341,7 @@ export function main() {
tick(1); tick(1);
expect(g.errors).toEqual({'async': true}); expect(g.errors).toEqual({'async': true});
expect(g.find(['one']).errors).toEqual({'async': true}); expect(g.get('one').errors).toEqual({'async': true});
})); }));
}); });
}); });
@ -1209,7 +1396,7 @@ export function main() {
}); });
}); });
describe('updateValue', () => { describe('setValue', () => {
let c: FormControl, c2: FormControl, a: FormArray; let c: FormControl, c2: FormControl, a: FormArray;
beforeEach(() => { beforeEach(() => {
@ -1218,40 +1405,41 @@ export function main() {
a = new FormArray([c, c2]); a = new FormArray([c, c2]);
}); });
it('should update its own value', () => { it('should set its own value', () => {
a.updateValue(['one', 'two']); a.setValue(['one', 'two']);
expect(a.value).toEqual(['one', 'two']); expect(a.value).toEqual(['one', 'two']);
}); });
it('should update child values', () => { it('should set child values', () => {
a.updateValue(['one', 'two']); a.setValue(['one', 'two']);
expect(c.value).toEqual('one'); expect(c.value).toEqual('one');
expect(c2.value).toEqual('two'); expect(c2.value).toEqual('two');
}); });
it('should update parent values', () => { it('should set parent values', () => {
const form = new FormGroup({'parent': a}); const form = new FormGroup({'parent': a});
a.updateValue(['one', 'two']); a.setValue(['one', 'two']);
expect(form.value).toEqual({'parent': ['one', 'two']}); expect(form.value).toEqual({'parent': ['one', 'two']});
}); });
it('should ignore fields that are missing from supplied value', () => { it('should throw if fields are missing from supplied value (subset)', () => {
a.updateValue([, 'two']); expect(() => a.setValue([, 'two']))
expect(a.value).toEqual(['', 'two']); .toThrowError(new RegExp(`Must supply a value for form control at index: 0`));
}); });
it('should not ignore fields that are null', () => { it('should throw if a value is provided for a missing control (superset)', () => {
a.updateValue([null]); expect(() => a.setValue([
expect(a.value).toEqual([null, '']); 'one', 'two', 'three'
});
it('should throw if a value is provided for a missing control', () => {
expect(() => a.updateValue([
, , 'three'
])).toThrowError(new RegExp(`Cannot find form control at index 2`)); ])).toThrowError(new RegExp(`Cannot find form control at index 2`));
}); });
describe('updateValue() events', () => { it('should throw if no controls are set yet', () => {
const empty = new FormArray([]);
expect(() => empty.setValue(['one']))
.toThrowError(new RegExp(`no form controls registered with this array`));
});
describe('setValue() events', () => {
let form: FormGroup; let form: FormGroup;
let logger: any[]; let logger: any[];
@ -1266,7 +1454,79 @@ export function main() {
c.valueChanges.subscribe(() => logger.push('control1')); c.valueChanges.subscribe(() => logger.push('control1'));
c2.valueChanges.subscribe(() => logger.push('control2')); c2.valueChanges.subscribe(() => logger.push('control2'));
a.updateValue(['one', 'two']); a.setValue(['one', 'two']);
expect(logger).toEqual(['control1', 'control2', 'array', 'form']);
});
it('should emit one statusChange event per control', () => {
form.statusChanges.subscribe(() => logger.push('form'));
a.statusChanges.subscribe(() => logger.push('array'));
c.statusChanges.subscribe(() => logger.push('control1'));
c2.statusChanges.subscribe(() => logger.push('control2'));
a.setValue(['one', 'two']);
expect(logger).toEqual(['control1', 'control2', 'array', 'form']);
});
});
});
describe('patchValue', () => {
let c: FormControl, c2: FormControl, a: FormArray;
beforeEach(() => {
c = new FormControl('');
c2 = new FormControl('');
a = new FormArray([c, c2]);
});
it('should set its own value', () => {
a.patchValue(['one', 'two']);
expect(a.value).toEqual(['one', 'two']);
});
it('should set child values', () => {
a.patchValue(['one', 'two']);
expect(c.value).toEqual('one');
expect(c2.value).toEqual('two');
});
it('should set parent values', () => {
const form = new FormGroup({'parent': a});
a.patchValue(['one', 'two']);
expect(form.value).toEqual({'parent': ['one', 'two']});
});
it('should ignore fields that are missing from supplied value (subset)', () => {
a.patchValue([, 'two']);
expect(a.value).toEqual(['', 'two']);
});
it('should not ignore fields that are null', () => {
a.patchValue([null]);
expect(a.value).toEqual([null, '']);
});
it('should ignore any value provided for a missing control (superset)', () => {
a.patchValue([, , 'three']);
expect(a.value).toEqual(['', '']);
});
describe('patchValue() events', () => {
let form: FormGroup;
let logger: any[];
beforeEach(() => {
form = new FormGroup({'parent': a});
logger = [];
});
it('should emit one valueChange event per control', () => {
form.valueChanges.subscribe(() => logger.push('form'));
a.valueChanges.subscribe(() => logger.push('array'));
c.valueChanges.subscribe(() => logger.push('control1'));
c2.valueChanges.subscribe(() => logger.push('control2'));
a.patchValue(['one', 'two']);
expect(logger).toEqual(['control1', 'control2', 'array', 'form']); expect(logger).toEqual(['control1', 'control2', 'array', 'form']);
}); });
@ -1276,7 +1536,7 @@ export function main() {
c.valueChanges.subscribe(() => logger.push('control1')); c.valueChanges.subscribe(() => logger.push('control1'));
c2.valueChanges.subscribe(() => logger.push('control2')); c2.valueChanges.subscribe(() => logger.push('control2'));
a.updateValue(['one']); a.patchValue(['one']);
expect(logger).toEqual(['control1', 'array', 'form']); expect(logger).toEqual(['control1', 'array', 'form']);
}); });
@ -1286,7 +1546,7 @@ export function main() {
c.statusChanges.subscribe(() => logger.push('control1')); c.statusChanges.subscribe(() => logger.push('control1'));
c2.statusChanges.subscribe(() => logger.push('control2')); c2.statusChanges.subscribe(() => logger.push('control2'));
a.updateValue(['one', 'two']); a.patchValue(['one', 'two']);
expect(logger).toEqual(['control1', 'control2', 'array', 'form']); expect(logger).toEqual(['control1', 'control2', 'array', 'form']);
}); });
}); });
@ -1302,7 +1562,7 @@ export function main() {
}); });
it('should set its own value if value passed', () => { it('should set its own value if value passed', () => {
a.updateValue(['new value', 'new value']); a.setValue(['new value', 'new value']);
a.reset(['initial value', '']); a.reset(['initial value', '']);
expect(a.value).toEqual(['initial value', '']); expect(a.value).toEqual(['initial value', '']);
@ -1310,14 +1570,14 @@ export function main() {
it('should clear its own value if no value passed', () => { it('should clear its own value if no value passed', () => {
a.updateValue(['new value', 'new value']); a.setValue(['new value', 'new value']);
a.reset(); a.reset();
expect(a.value).toEqual([null, null]); expect(a.value).toEqual([null, null]);
}); });
it('should set the value of each of its child controls if value passed', () => { it('should set the value of each of its child controls if value passed', () => {
a.updateValue(['new value', 'new value']); a.setValue(['new value', 'new value']);
a.reset(['initial value', '']); a.reset(['initial value', '']);
expect(c.value).toBe('initial value'); expect(c.value).toBe('initial value');
@ -1325,7 +1585,7 @@ export function main() {
}); });
it('should clear the value of each of its child controls if no value', () => { it('should clear the value of each of its child controls if no value', () => {
a.updateValue(['new value', 'new value']); a.setValue(['new value', 'new value']);
a.reset(); a.reset();
expect(c.value).toBe(null); expect(c.value).toBe(null);
@ -1334,7 +1594,7 @@ export function main() {
it('should set the value of its parent if value passed', () => { it('should set the value of its parent if value passed', () => {
const form = new FormGroup({'a': a}); const form = new FormGroup({'a': a});
a.updateValue(['new value', 'new value']); a.setValue(['new value', 'new value']);
a.reset(['initial value', '']); a.reset(['initial value', '']);
expect(form.value).toEqual({'a': ['initial value', '']}); expect(form.value).toEqual({'a': ['initial value', '']});
@ -1342,7 +1602,7 @@ export function main() {
it('should clear the value of its parent if no value passed', () => { it('should clear the value of its parent if no value passed', () => {
const form = new FormGroup({'a': a}); const form = new FormGroup({'a': a});
a.updateValue(['new value', 'new value']); a.setValue(['new value', 'new value']);
a.reset(); a.reset();
expect(form.value).toEqual({'a': [null, null]}); expect(form.value).toEqual({'a': [null, null]});
@ -1473,12 +1733,12 @@ export function main() {
var c = new FormControl(null); var c = new FormControl(null);
var g = new FormArray([c], simpleValidator); var g = new FormArray([c], simpleValidator);
c.updateValue('correct'); c.setValue('correct');
expect(g.valid).toEqual(true); expect(g.valid).toEqual(true);
expect(g.errors).toEqual(null); expect(g.errors).toEqual(null);
c.updateValue('incorrect'); c.setValue('incorrect');
expect(g.valid).toEqual(false); expect(g.valid).toEqual(false);
expect(g.errors).toEqual({'broken': true}); expect(g.errors).toEqual({'broken': true});
@ -1571,7 +1831,7 @@ export function main() {
async.done(); async.done();
} }
}); });
c1.updateValue('new1'); c1.setValue('new1');
})); }));
it('should fire an event after the control\'s observable fired an event', it('should fire an event after the control\'s observable fired an event',
@ -1588,7 +1848,7 @@ export function main() {
} }
}); });
c1.updateValue('new1'); c1.setValue('new1');
})); }));
it('should fire an event when a control is removed', it('should fire an event when a control is removed',

View File

@ -198,7 +198,7 @@ export function main() {
fixture.debugElement.componentInstance.form = form; fixture.debugElement.componentInstance.form = form;
fixture.detectChanges(); fixture.detectChanges();
login.updateValue('newValue'); login.setValue('newValue');
fixture.detectChanges(); fixture.detectChanges();
@ -276,7 +276,7 @@ export function main() {
fixture.debugElement.componentInstance.form = form; fixture.debugElement.componentInstance.form = form;
fixture.detectChanges(); fixture.detectChanges();
login.updateValue('new value'); login.setValue('new value');
const loginEl = fixture.debugElement.query(By.css('input')).nativeElement; const loginEl = fixture.debugElement.query(By.css('input')).nativeElement;
expect(loginEl.value).toBe('new value'); expect(loginEl.value).toBe('new value');
@ -302,7 +302,7 @@ export function main() {
fixture.debugElement.componentInstance.form = form; fixture.debugElement.componentInstance.form = form;
fixture.detectChanges(); fixture.detectChanges();
login.updateValue('new value'); login.setValue('new value');
const loginEl = fixture.debugElement.query(By.css('input')).nativeElement; const loginEl = fixture.debugElement.query(By.css('input')).nativeElement;
expect(loginEl.value).toBe('new value'); expect(loginEl.value).toBe('new value');
@ -654,7 +654,7 @@ export function main() {
expect(value.food).toEqual('chicken'); expect(value.food).toEqual('chicken');
expect(inputs[1].nativeElement.checked).toEqual(false); expect(inputs[1].nativeElement.checked).toEqual(false);
ctrl.updateValue('fish'); ctrl.setValue('fish');
fixture.detectChanges(); fixture.detectChanges();
expect(inputs[0].nativeElement.checked).toEqual(false); expect(inputs[0].nativeElement.checked).toEqual(false);
@ -698,7 +698,7 @@ export function main() {
expect(inputs[2].nativeElement.checked).toEqual(false); expect(inputs[2].nativeElement.checked).toEqual(false);
expect(inputs[3].nativeElement.checked).toEqual(true); expect(inputs[3].nativeElement.checked).toEqual(true);
drinkCtrl.updateValue('cola'); drinkCtrl.setValue('cola');
fixture.detectChanges(); fixture.detectChanges();
expect(inputs[0].nativeElement.checked).toEqual(true); expect(inputs[0].nativeElement.checked).toEqual(true);

View File

@ -39,6 +39,7 @@ export declare abstract class AbstractControl {
markAsUntouched({onlySelf}?: { markAsUntouched({onlySelf}?: {
onlySelf?: boolean; onlySelf?: boolean;
}): void; }): void;
abstract patchValue(value: any, options?: Object): void;
abstract reset(value?: any, options?: Object): void; abstract reset(value?: any, options?: Object): void;
setAsyncValidators(newValidator: AsyncValidatorFn | AsyncValidatorFn[]): void; setAsyncValidators(newValidator: AsyncValidatorFn | AsyncValidatorFn[]): void;
setErrors(errors: { setErrors(errors: {
@ -48,7 +49,7 @@ export declare abstract class AbstractControl {
}): void; }): void;
setParent(parent: FormGroup | FormArray): void; setParent(parent: FormGroup | FormArray): void;
setValidators(newValidator: ValidatorFn | ValidatorFn[]): void; setValidators(newValidator: ValidatorFn | ValidatorFn[]): void;
abstract updateValue(value: any, options?: Object): void; abstract setValue(value: any, options?: Object): void;
updateValueAndValidity({onlySelf, emitEvent}?: { updateValueAndValidity({onlySelf, emitEvent}?: {
onlySelf?: boolean; onlySelf?: boolean;
emitEvent?: boolean; emitEvent?: boolean;
@ -152,12 +153,15 @@ export declare class FormArray extends AbstractControl {
constructor(controls: AbstractControl[], validator?: ValidatorFn, asyncValidator?: AsyncValidatorFn); constructor(controls: AbstractControl[], validator?: ValidatorFn, asyncValidator?: AsyncValidatorFn);
at(index: number): AbstractControl; at(index: number): AbstractControl;
insert(index: number, control: AbstractControl): void; insert(index: number, control: AbstractControl): void;
patchValue(value: any[], {onlySelf}?: {
onlySelf?: boolean;
}): void;
push(control: AbstractControl): void; push(control: AbstractControl): void;
removeAt(index: number): void; removeAt(index: number): void;
reset(value?: any, {onlySelf}?: { reset(value?: any, {onlySelf}?: {
onlySelf?: boolean; onlySelf?: boolean;
}): void; }): void;
updateValue(value: any[], {onlySelf}?: { setValue(value: any[], {onlySelf}?: {
onlySelf?: boolean; onlySelf?: boolean;
}): void; }): void;
} }
@ -189,11 +193,23 @@ export declare class FormBuilder {
/** @experimental */ /** @experimental */
export declare class FormControl extends AbstractControl { export declare class FormControl extends AbstractControl {
constructor(value?: any, validator?: ValidatorFn | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]); constructor(value?: any, validator?: ValidatorFn | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]);
patchValue(value: any, options?: {
onlySelf?: boolean;
emitEvent?: boolean;
emitModelToViewChange?: boolean;
emitViewToModelChange?: boolean;
}): void;
registerOnChange(fn: Function): void; registerOnChange(fn: Function): void;
reset(value?: any, {onlySelf}?: { reset(value?: any, {onlySelf}?: {
onlySelf?: boolean; onlySelf?: boolean;
}): void; }): void;
updateValue(value: any, {onlySelf, emitEvent, emitModelToViewChange, emitViewToModelChange}?: { setValue(value: any, {onlySelf, emitEvent, emitModelToViewChange, emitViewToModelChange}?: {
onlySelf?: boolean;
emitEvent?: boolean;
emitModelToViewChange?: boolean;
emitViewToModelChange?: boolean;
}): void;
/** @deprecated */ updateValue(value: any, options?: {
onlySelf?: boolean; onlySelf?: boolean;
emitEvent?: boolean; emitEvent?: boolean;
emitModelToViewChange?: boolean; emitModelToViewChange?: boolean;
@ -246,12 +262,17 @@ export declare class FormGroup extends AbstractControl {
contains(controlName: string): boolean; contains(controlName: string): boolean;
exclude(controlName: string): void; exclude(controlName: string): void;
include(controlName: string): void; include(controlName: string): void;
patchValue(value: {
[key: string]: any;
}, {onlySelf}?: {
onlySelf?: boolean;
}): void;
registerControl(name: string, control: AbstractControl): AbstractControl; registerControl(name: string, control: AbstractControl): AbstractControl;
removeControl(name: string): void; removeControl(name: string): void;
reset(value?: any, {onlySelf}?: { reset(value?: any, {onlySelf}?: {
onlySelf?: boolean; onlySelf?: boolean;
}): void; }): void;
updateValue(value: { setValue(value: {
[key: string]: any; [key: string]: any;
}, {onlySelf}?: { }, {onlySelf}?: {
onlySelf?: boolean; onlySelf?: boolean;
@ -358,10 +379,10 @@ export declare class NgForm extends ControlContainer implements Form {
onSubmit(): boolean; onSubmit(): boolean;
removeControl(dir: NgModel): void; removeControl(dir: NgModel): void;
removeFormGroup(dir: NgModelGroup): void; removeFormGroup(dir: NgModelGroup): void;
updateModel(dir: NgControl, value: any): void; setValue(value: {
updateValue(value: {
[key: string]: any; [key: string]: any;
}): void; }): void;
updateModel(dir: NgControl, value: any): void;
} }
/** @experimental */ /** @experimental */