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 {
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 {
resolvedPromise.then(() => {
var ctrl = <FormControl>this.form.find(dir.path);
ctrl.updateValue(value);
var ctrl = <FormControl>this.form.get(dir.path);
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 {
this._submitted = true;
@ -179,6 +179,6 @@ export class NgForm extends ControlContainer implements Form {
/** @internal */
_findContainer(path: string[]): FormGroup {
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 {
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});
}
if (isPropertyUpdated(changes, this.viewModel)) {
this.form.updateValue(this.model);
this.form.setValue(this.model);
this.viewModel = this.model;
}
}

View File

@ -145,39 +145,39 @@ export class FormGroupDirective extends ControlContainer implements Form,
get path(): string[] { return []; }
addControl(dir: NgControl): void {
const ctrl: any = this.form.find(dir.path);
const ctrl: any = this.form.get(dir.path);
setUpControl(ctrl, dir);
ctrl.updateValueAndValidity({emitEvent: false});
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); }
addFormGroup(dir: FormGroupName): void {
var ctrl: any = this.form.find(dir.path);
var ctrl: any = this.form.get(dir.path);
setUpFormContainer(ctrl, dir);
ctrl.updateValueAndValidity({emitEvent: false});
}
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 {
var ctrl: any = this.form.find(dir.path);
var ctrl: any = this.form.get(dir.path);
setUpFormContainer(ctrl, dir);
ctrl.updateValueAndValidity({emitEvent: false});
}
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 {
var ctrl  = <FormControl>this.form.find(dir.path);
ctrl.updateValue(value);
var ctrl  = <FormControl>this.form.get(dir.path);
ctrl.setValue(value);
}
onSubmit(): boolean {
@ -191,7 +191,7 @@ export class FormGroupDirective extends ControlContainer implements Form,
/** @internal */
_updateDomValue() {
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);
});
}

View File

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

View File

@ -177,7 +177,9 @@ export abstract class AbstractControl {
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;
@ -401,7 +403,7 @@ export class FormControl extends AbstractControl {
* If `emitViewToModelChange` is `true`, an ngModelChange event will be fired to update the
* 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,
emitEvent?: boolean,
emitModelToViewChange?: boolean,
@ -417,10 +419,35 @@ export class FormControl extends AbstractControl {
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 {
this.markAsPristine({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);
}
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) => {
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});
}
@ -542,6 +579,12 @@ export class FormGroup extends AbstractControl {
/** @internal */
_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]) {
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);
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; }
updateValue(value: any[], {onlySelf}: {onlySelf?: boolean} = {}): void {
setValue(value: any[], {onlySelf}: {onlySelf?: boolean} = {}): void {
this._checkAllValuesPresent(value);
value.forEach((newValue: any, index: number) => {
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});
}
@ -685,6 +747,12 @@ export class FormArray extends AbstractControl {
/** @internal */
_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)) {
throw new BaseException(`Cannot find form control at index ${index}`);
}
@ -707,4 +775,13 @@ export class FormArray extends AbstractControl {
_setParentForControls(): void {
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('async', ['login'])).toBe(false);
(<FormControl>formModel.find(['login'])).updateValue('invalid value');
(<FormControl>formModel.get('login')).setValue('invalid value');
// sync validator passes, running async validators
expect(formModel.pending).toBe(true);
@ -205,7 +205,7 @@ export function main() {
}));
it('should write value to the DOM', () => {
(<FormControl>formModel.find(['login'])).updateValue('initValue');
(<FormControl>formModel.get(['login'])).setValue('initValue');
form.addControl(loginControlDir);
@ -233,17 +233,17 @@ export function main() {
group.name = 'passwords';
form.addFormGroup(group);
(<FormControl>formModel.find(['passwords', 'password'])).updateValue('somePassword');
(<FormControl>formModel.find([
(<FormControl>formModel.get(['passwords', 'password'])).setValue('somePassword');
(<FormControl>formModel.get([
'passwords', 'passwordConfirm'
])).updateValue('someOtherPassword');
])).setValue('someOtherPassword');
// sync validators are set
expect(formModel.hasError('differentPasswords', ['passwords'])).toEqual(true);
(<FormControl>formModel.find([
(<FormControl>formModel.get([
'passwords', 'passwordConfirm'
])).updateValue('somePassword');
])).setValue('somePassword');
// sync validators pass, running async validators
expect(formModel.pending).toBe(true);
@ -266,7 +266,7 @@ export function main() {
it('should update dom values of all the directives', () => {
form.addControl(loginControlDir);
(<FormControl>formModel.find(['login'])).updateValue('new value');
(<FormControl>formModel.get(['login'])).setValue('new value');
form.ngOnChanges({});
@ -334,7 +334,7 @@ export function main() {
flushMicrotasks();
expect(formModel.find(['person', 'login'])).not.toBeNull;
expect(formModel.get(['person', 'login'])).not.toBeNull;
}));
// should update the form's value and validity
@ -350,8 +350,8 @@ export function main() {
flushMicrotasks();
expect(formModel.find(['person'])).toBeNull();
expect(formModel.find(['person', 'login'])).toBeNull();
expect(formModel.get(['person'])).toBeNull();
expect(formModel.get(['person', 'login'])).toBeNull();
}));
// should update the form's value and validity
@ -524,7 +524,7 @@ export function main() {
expect(ngModel.control.errors).toEqual({'required': true});
ngModel.control.updateValue('someValue');
ngModel.control.setValue('someValue');
tick();
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', () => {
var c = new FormControl('value', Validators.required);
c.updateValue(null);
c.setValue(null);
expect(c.valid).toEqual(false);
});
it('should support arrays of validator functions if passed', () => {
const c = new FormControl('value', [Validators.required, Validators.minLength(3)]);
c.updateValue('a');
c.setValue('a');
expect(c.valid).toEqual(false);
c.updateValue('aaa');
c.setValue('aaa');
expect(c.valid).toEqual(true);
});
@ -80,10 +80,10 @@ export function main() {
c.setValidators(Validators.required);
c.updateValue(null);
c.setValue(null);
expect(c.valid).toEqual(false);
c.updateValue('abc');
c.setValue('abc');
expect(c.valid).toEqual(true);
});
@ -93,13 +93,13 @@ export function main() {
c.setValidators([Validators.minLength(5), Validators.required]);
c.updateValue('');
c.setValue('');
expect(c.valid).toEqual(false);
c.updateValue('abc');
c.setValue('abc');
expect(c.valid).toEqual(false);
c.updateValue('abcde');
c.setValue('abcde');
expect(c.valid).toEqual(true);
});
@ -110,7 +110,7 @@ export function main() {
c.clearValidators();
expect(c.validator).toEqual(null);
c.updateValue('');
c.setValue('');
expect(c.valid).toEqual(true);
});
@ -146,7 +146,7 @@ export function main() {
it('should rerun the validator when the value changes', fakeAsync(() => {
var c = new FormControl('value', null, asyncValidator('expected'));
c.updateValue('expected');
c.setValue('expected');
tick();
expect(c.valid).toEqual(true);
@ -158,7 +158,7 @@ export function main() {
expect(c.errors).toEqual({'required': true});
c.updateValue('some value');
c.setValue('some value');
tick();
expect(c.errors).toEqual({'async': true});
@ -179,8 +179,8 @@ export function main() {
var c = new FormControl(
'', null, asyncValidator('expected', {'long': 200, 'expected': 100}));
c.updateValue('long');
c.updateValue('expected');
c.setValue('long');
c.setValue('expected');
tick(300);
@ -201,7 +201,7 @@ export function main() {
c.setAsyncValidators(asyncValidator('expected'));
expect(c.asyncValidator).not.toEqual(null);
c.updateValue('expected');
c.setValue('expected');
tick();
expect(c.valid).toEqual(true);
@ -213,7 +213,7 @@ export function main() {
c.setAsyncValidators([asyncValidator('expected')]);
expect(c.asyncValidator).not.toEqual(null);
c.updateValue('expected');
c.setValue('expected');
tick();
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', () => {
var g: any /** TODO #9100 */, c: any /** TODO #9100 */;
beforeEach(() => {
@ -318,7 +431,7 @@ export function main() {
beforeEach(() => { c = new FormControl('initial value'); });
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');
c.reset('initial value');
@ -326,7 +439,7 @@ export function main() {
});
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');
c.reset();
@ -335,7 +448,7 @@ export function main() {
it('should update the value of any parent controls with passed value', () => {
const g = new FormGroup({'one': c});
c.updateValue('new value');
c.setValue('new value');
expect(g.value).toEqual({'one': 'new value'});
c.reset('initial value');
@ -344,7 +457,7 @@ export function main() {
it('should update the value of any parent controls with null value', () => {
const g = new FormGroup({'one': c});
c.updateValue('new value');
c.setValue('new value');
expect(g.value).toEqual({'one': 'new value'});
c.reset();
@ -450,7 +563,7 @@ export function main() {
async.done();
}
});
c.updateValue('new');
c.setValue('new');
}));
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();
}));
@ -473,13 +586,13 @@ export function main() {
c.statusChanges.subscribe({next: (status: any) => log.push(`status: '${status}'`)});
c.updateValue('');
c.setValue('');
tick();
c.updateValue('nonEmpty');
c.setValue('nonEmpty');
tick();
c.updateValue('expected');
c.setValue('expected');
tick();
expect(log).toEqual([
@ -503,19 +616,19 @@ export function main() {
expect(c.errors).toEqual({'required': true});
async.done();
});
c.updateValue('');
c.setValue('');
}));
it('should return a cold observable',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
c.updateValue('will be ignored');
c.setValue('will be ignored');
c.valueChanges.subscribe({
next: (value: any) => {
expect(value).toEqual('new');
async.done();
}
});
c.updateValue('new');
c.setValue('new');
}));
});
@ -533,7 +646,7 @@ export function main() {
var c = new FormControl('someValue', Validators.required);
c.setErrors({'someError': true});
c.updateValue('');
c.setValue('');
expect(c.errors).toEqual({'required': true});
});
@ -566,7 +679,7 @@ export function main() {
g.setErrors({'someGroupError': true});
c.setErrors({'someError': true});
c.updateValue('newValue');
c.setValue('newValue');
expect(c.errors).toEqual(null);
expect(g.errors).toEqual(null);
@ -593,7 +706,7 @@ export function main() {
});
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'}});
});
@ -632,12 +745,12 @@ export function main() {
var c = new FormControl(null);
var g = new FormGroup({'one': c}, null, simpleValidator);
c.updateValue('correct');
c.setValue('correct');
expect(g.valid).toEqual(true);
expect(g.errors).toEqual(null);
c.updateValue('incorrect');
c.setValue('incorrect');
expect(g.valid).toEqual(false);
expect(g.errors).toEqual({'broken': true});
@ -679,7 +792,7 @@ export function main() {
});
});
describe('updateValue', () => {
describe('setValue', () => {
let c: FormControl, c2: FormControl, g: FormGroup;
beforeEach(() => {
@ -688,40 +801,42 @@ export function main() {
g = new FormGroup({'one': c, 'two': c2});
});
it('should update its own value', () => {
g.updateValue({'one': 'one', 'two': 'two'});
it('should set its own value', () => {
g.setValue({'one': 'one', 'two': 'two'});
expect(g.value).toEqual({'one': 'one', 'two': 'two'});
});
it('should update child values', () => {
g.updateValue({'one': 'one', 'two': 'two'});
it('should set child values', () => {
g.setValue({'one': 'one', 'two': 'two'});
expect(c.value).toEqual('one');
expect(c2.value).toEqual('two');
});
it('should update parent values', () => {
it('should set parent values', () => {
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'}});
});
it('should ignore fields that are missing from supplied value', () => {
g.updateValue({'one': 'one'});
expect(g.value).toEqual({'one': 'one', 'two': ''});
it('should throw if fields are missing from supplied value (subset)', () => {
expect(() => g.setValue({
'one': 'one'
})).toThrowError(new RegExp(`Must supply a value for form control with name: 'two'`));
});
it('should not ignore fields that are null', () => {
g.updateValue({'one': null});
expect(g.value).toEqual({'one': null, 'two': ''});
it('should throw if a value is provided for a missing control (superset)', () => {
expect(() => g.setValue({'one': 'one', 'two': 'two', 'three': 'three'}))
.toThrowError(new RegExp(`Cannot find form control with name: three`));
});
it('should throw if a value is provided for a missing control', () => {
expect(() => g.updateValue({
'three': 'three'
})).toThrowError(new RegExp(`Cannot find form control with name: three`));
it('should throw if no controls are set yet', () => {
const empty = new FormGroup({});
expect(() => empty.setValue({
'one': 'one'
})).toThrowError(new RegExp(`no form controls registered with this group`));
});
describe('updateValue() events', () => {
describe('setValue() events', () => {
let form: FormGroup;
let logger: any[];
@ -736,7 +851,79 @@ export function main() {
c.valueChanges.subscribe(() => logger.push('control1'));
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']);
});
@ -746,7 +933,7 @@ export function main() {
c.valueChanges.subscribe(() => logger.push('control1'));
c2.valueChanges.subscribe(() => logger.push('control2'));
g.updateValue({'one': 'one'});
g.patchValue({'one': 'one'});
expect(logger).toEqual(['control1', 'group', 'form']);
});
@ -756,7 +943,7 @@ export function main() {
c.statusChanges.subscribe(() => logger.push('control1'));
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']);
});
});
@ -772,21 +959,21 @@ export function main() {
});
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': ''});
expect(g.value).toEqual({'one': 'initial value', 'two': ''});
});
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();
expect(g.value).toEqual({'one': null, 'two': null});
});
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': ''});
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', () => {
g.updateValue({'one': 'new value', 'two': 'new value'});
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset();
expect(c.value).toBe(null);
@ -803,7 +990,7 @@ export function main() {
it('should set the value of its parent if value passed', () => {
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': ''});
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', () => {
const form = new FormGroup({'g': g});
g.updateValue({'one': 'new value', 'two': 'new value'});
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset();
expect(form.value).toEqual({'g': {'one': null, 'two': null}});
@ -1013,7 +1200,7 @@ export function main() {
async.done();
}
});
c1.updateValue('new1');
c1.setValue('new1');
}));
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',
@ -1076,8 +1263,8 @@ export function main() {
}
});
c1.updateValue('new1');
c2.updateValue('new2');
c1.setValue('new1');
c2.setValue('new2');
}));
// hard to test without hacking zones
@ -1101,7 +1288,7 @@ export function main() {
async.done();
}
});
control.updateValue('');
control.setValue('');
}));
});
@ -1154,7 +1341,7 @@ export function main() {
tick(1);
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;
beforeEach(() => {
@ -1218,40 +1405,41 @@ export function main() {
a = new FormArray([c, c2]);
});
it('should update its own value', () => {
a.updateValue(['one', 'two']);
it('should set its own value', () => {
a.setValue(['one', 'two']);
expect(a.value).toEqual(['one', 'two']);
});
it('should update child values', () => {
a.updateValue(['one', 'two']);
it('should set child values', () => {
a.setValue(['one', 'two']);
expect(c.value).toEqual('one');
expect(c2.value).toEqual('two');
});
it('should update parent values', () => {
it('should set parent values', () => {
const form = new FormGroup({'parent': a});
a.updateValue(['one', 'two']);
a.setValue(['one', 'two']);
expect(form.value).toEqual({'parent': ['one', 'two']});
});
it('should ignore fields that are missing from supplied value', () => {
a.updateValue([, 'two']);
expect(a.value).toEqual(['', 'two']);
it('should throw if fields are missing from supplied value (subset)', () => {
expect(() => a.setValue([, 'two']))
.toThrowError(new RegExp(`Must supply a value for form control at index: 0`));
});
it('should not ignore fields that are null', () => {
a.updateValue([null]);
expect(a.value).toEqual([null, '']);
});
it('should throw if a value is provided for a missing control', () => {
expect(() => a.updateValue([
, , 'three'
it('should throw if a value is provided for a missing control (superset)', () => {
expect(() => a.setValue([
'one', 'two', 'three'
])).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 logger: any[];
@ -1266,7 +1454,79 @@ export function main() {
c.valueChanges.subscribe(() => logger.push('control1'));
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']);
});
@ -1276,7 +1536,7 @@ export function main() {
c.valueChanges.subscribe(() => logger.push('control1'));
c2.valueChanges.subscribe(() => logger.push('control2'));
a.updateValue(['one']);
a.patchValue(['one']);
expect(logger).toEqual(['control1', 'array', 'form']);
});
@ -1286,7 +1546,7 @@ export function main() {
c.statusChanges.subscribe(() => logger.push('control1'));
c2.statusChanges.subscribe(() => logger.push('control2'));
a.updateValue(['one', 'two']);
a.patchValue(['one', 'two']);
expect(logger).toEqual(['control1', 'control2', 'array', 'form']);
});
});
@ -1302,7 +1562,7 @@ export function main() {
});
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', '']);
expect(a.value).toEqual(['initial value', '']);
@ -1310,14 +1570,14 @@ export function main() {
it('should clear its own value if no value passed', () => {
a.updateValue(['new value', 'new value']);
a.setValue(['new value', 'new value']);
a.reset();
expect(a.value).toEqual([null, null]);
});
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', '']);
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', () => {
a.updateValue(['new value', 'new value']);
a.setValue(['new value', 'new value']);
a.reset();
expect(c.value).toBe(null);
@ -1334,7 +1594,7 @@ export function main() {
it('should set the value of its parent if value passed', () => {
const form = new FormGroup({'a': a});
a.updateValue(['new value', 'new value']);
a.setValue(['new value', 'new value']);
a.reset(['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', () => {
const form = new FormGroup({'a': a});
a.updateValue(['new value', 'new value']);
a.setValue(['new value', 'new value']);
a.reset();
expect(form.value).toEqual({'a': [null, null]});
@ -1473,12 +1733,12 @@ export function main() {
var c = new FormControl(null);
var g = new FormArray([c], simpleValidator);
c.updateValue('correct');
c.setValue('correct');
expect(g.valid).toEqual(true);
expect(g.errors).toEqual(null);
c.updateValue('incorrect');
c.setValue('incorrect');
expect(g.valid).toEqual(false);
expect(g.errors).toEqual({'broken': true});
@ -1571,7 +1831,7 @@ export function main() {
async.done();
}
});
c1.updateValue('new1');
c1.setValue('new1');
}));
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',

View File

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

View File

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