chore(forms): rename Control, ControlGroup, and ControlArray classes

This commit is contained in:
Kara Erickson 2016-06-10 11:15:59 -07:00
parent 97833d48c1
commit b866f32832
21 changed files with 328 additions and 314 deletions

View File

@ -1,9 +1,10 @@
/** /**
* @module * @module
* @description * @description
* This module is used for handling user input, by defining and building a {@link ControlGroup} that * This module is used for handling user input, by defining and building a {@link FormGroup} that
* consists of * consists of
* {@link Control} objects, and mapping them onto the DOM. {@link Control} objects can then be used * {@link FormControl} objects, and mapping them onto the DOM. {@link FormControl} objects can then
* be used
* to read information * to read information
* from the form DOM elements. * from the form DOM elements.
* *
@ -33,10 +34,11 @@ export {NgModel} from './forms/directives/ng_model';
export {NgSelectOption, SelectControlValueAccessor} from './forms/directives/select_control_value_accessor'; export {NgSelectOption, SelectControlValueAccessor} from './forms/directives/select_control_value_accessor';
export {MaxLengthValidator, MinLengthValidator, PatternValidator, RequiredValidator, Validator} from './forms/directives/validators'; export {MaxLengthValidator, MinLengthValidator, PatternValidator, RequiredValidator, Validator} from './forms/directives/validators';
export {FormBuilder} from './forms/form_builder'; export {FormBuilder} from './forms/form_builder';
export {AbstractControl, Control, ControlArray, ControlGroup} from './forms/model'; export {AbstractControl, FormArray, FormControl, FormGroup} from './forms/model';
export {NG_ASYNC_VALIDATORS, NG_VALIDATORS, Validators} from './forms/validators'; export {NG_ASYNC_VALIDATORS, NG_VALIDATORS, Validators} from './forms/validators';
/** /**
* Shorthand set of providers used for building Angular forms. * Shorthand set of providers used for building Angular forms.
* *

View File

@ -1,4 +1,4 @@
import {Control, ControlGroup} from '../model'; import {FormControl, FormGroup} from '../model';
import {NgControl} from './ng_control'; import {NgControl} from './ng_control';
import {NgControlGroup} from './ng_control_group'; import {NgControlGroup} from './ng_control_group';
@ -15,7 +15,7 @@ export interface Form {
/** /**
* Add a control to this form. * Add a control to this form.
*/ */
addControl(dir: NgControl): Control; addControl(dir: NgControl): FormControl;
/** /**
* Remove a control from this form. * Remove a control from this form.
@ -25,22 +25,22 @@ export interface Form {
/** /**
* Look up the {@link Control} associated with a particular {@link NgControl}. * Look up the {@link Control} associated with a particular {@link NgControl}.
*/ */
getControl(dir: NgControl): Control; getControl(dir: NgControl): FormControl;
/** /**
* Add a group of controls to this form. * Add a group of controls to this form.
*/ */
addControlGroup(dir: NgControlGroup): void; addFormGroup(dir: NgControlGroup): void;
/** /**
* Remove a group of controls from this form. * Remove a group of controls from this form.
*/ */
removeControlGroup(dir: NgControlGroup): void; removeFormGroup(dir: NgControlGroup): void;
/** /**
* Look up the {@link ControlGroup} associated with a particular {@link NgControlGroup}. * Look up the {@link FormGroup} associated with a particular {@link NgControlGroup}.
*/ */
getControlGroup(dir: NgControlGroup): ControlGroup; getFormGroup(dir: NgControlGroup): FormGroup;
/** /**
* Update the model for a particular control with a new value. * Update the model for a particular control with a new value.

View File

@ -1,6 +1,6 @@
import {Directive, Host, Inject, OnDestroy, OnInit, Optional, Self, SkipSelf, forwardRef} from '@angular/core'; import {Directive, Host, Inject, OnDestroy, OnInit, Optional, Self, SkipSelf, forwardRef} from '@angular/core';
import {ControlGroup} from '../model'; import {FormGroup} from '../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators'; import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';
import {ControlContainer} from './control_container'; import {ControlContainer} from './control_container';
@ -26,7 +26,7 @@ export const controlGroupProvider: any =
* selector: 'my-app', * selector: 'my-app',
* template: ` * template: `
* <div> * <div>
* <h2>Angular Control &amp; ControlGroup Example</h2> * <h2>Angular FormControl &amp; FormGroup Example</h2>
* <form #f="ngForm"> * <form #f="ngForm">
* <div ngControlGroup="name" #cgName="ngForm"> * <div ngControlGroup="name" #cgName="ngForm">
* <h3>Enter your name:</h3> * <h3>Enter your name:</h3>
@ -79,14 +79,14 @@ export class NgControlGroup extends ControlContainer implements OnInit,
this._parent = parent; this._parent = parent;
} }
ngOnInit(): void { this.formDirective.addControlGroup(this); } ngOnInit(): void { this.formDirective.addFormGroup(this); }
ngOnDestroy(): void { this.formDirective.removeControlGroup(this); } ngOnDestroy(): void { this.formDirective.removeFormGroup(this); }
/** /**
* Get the {@link ControlGroup} backing this binding. * Get the {@link FormGroup} backing this binding.
*/ */
get control(): ControlGroup { return this.formDirective.getControlGroup(this); } get control(): FormGroup { return this.formDirective.getFormGroup(this); }
/** /**
* Get the path to this control group. * Get the path to this control group.

View File

@ -1,7 +1,7 @@
import {Directive, Host, Inject, OnChanges, OnDestroy, Optional, Self, SimpleChanges, SkipSelf, forwardRef} from '@angular/core'; import {Directive, Host, Inject, OnChanges, OnDestroy, Optional, Self, SimpleChanges, SkipSelf, forwardRef} from '@angular/core';
import {EventEmitter, ObservableWrapper} from '../../facade/async'; import {EventEmitter, ObservableWrapper} from '../../facade/async';
import {Control} from '../model'; import {FormControl} from '../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators'; import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';
import {ControlContainer} from './control_container'; import {ControlContainer} from './control_container';
@ -128,5 +128,5 @@ export class NgControlName extends NgControl implements OnChanges,
return composeAsyncValidators(this._asyncValidators); return composeAsyncValidators(this._asyncValidators);
} }
get control(): Control { return this.formDirective.getControl(this); } get control(): FormControl { return this.formDirective.getControl(this); }
} }

View File

@ -3,14 +3,14 @@ import {Directive, Inject, Optional, Self, forwardRef} from '@angular/core';
import {EventEmitter, ObservableWrapper, PromiseWrapper} from '../../facade/async'; import {EventEmitter, ObservableWrapper, PromiseWrapper} from '../../facade/async';
import {ListWrapper} from '../../facade/collection'; import {ListWrapper} from '../../facade/collection';
import {isPresent} from '../../facade/lang'; import {isPresent} from '../../facade/lang';
import {AbstractControl, Control, ControlGroup} from '../model'; import {AbstractControl, FormControl, FormGroup} from '../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators'; import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';
import {ControlContainer} from './control_container'; import {ControlContainer} from './control_container';
import {Form} from './form_interface'; import {Form} from './form_interface';
import {NgControl} from './ng_control'; import {NgControl} from './ng_control';
import {NgControlGroup} from './ng_control_group'; import {NgControlGroup} from './ng_control_group';
import {composeAsyncValidators, composeValidators, setUpControl, setUpControlGroup} from './shared'; import {composeAsyncValidators, composeValidators, setUpControl, setUpFormGroup} from './shared';
export const formDirectiveProvider: any = export const formDirectiveProvider: any =
/*@ts2dart_const*/ {provide: ControlContainer, useExisting: forwardRef(() => NgForm)}; /*@ts2dart_const*/ {provide: ControlContainer, useExisting: forwardRef(() => NgForm)};
@ -26,9 +26,9 @@ export const formDirectiveProvider: any =
* *
* ### Structure * ### Structure
* *
* An Angular form is a collection of `Control`s in some hierarchy. * An Angular form is a collection of `FormControl`s in some hierarchy.
* `Control`s can be at the top level or can be organized in `ControlGroup`s * `FormControl`s can be at the top level or can be organized in `FormGroup`s
* or `ControlArray`s. This hierarchy is reflected in the form's `value`, a * or `FormArray`s. This hierarchy is reflected in the form's `value`, a
* JSON object that mirrors the form structure. * JSON object that mirrors the form structure.
* *
* ### Submission * ### Submission
@ -88,14 +88,14 @@ export const formDirectiveProvider: any =
export class NgForm extends ControlContainer implements Form { export class NgForm extends ControlContainer implements Form {
private _submitted: boolean = false; private _submitted: boolean = false;
form: ControlGroup; form: FormGroup;
ngSubmit = new EventEmitter(); ngSubmit = new EventEmitter();
constructor( constructor(
@Optional() @Self() @Inject(NG_VALIDATORS) validators: any[], @Optional() @Self() @Inject(NG_VALIDATORS) validators: any[],
@Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: any[]) { @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: any[]) {
super(); super();
this.form = new ControlGroup( this.form = new FormGroup(
{}, null, composeValidators(validators), composeAsyncValidators(asyncValidators)); {}, null, composeValidators(validators), composeAsyncValidators(asyncValidators));
} }
@ -103,14 +103,14 @@ export class NgForm extends ControlContainer implements Form {
get formDirective(): Form { return this; } get formDirective(): Form { return this; }
get control(): ControlGroup { return this.form; } get control(): FormGroup { return this.form; }
get path(): string[] { return []; } get path(): string[] { return []; }
get controls(): {[key: string]: AbstractControl} { return this.form.controls; } get controls(): {[key: string]: AbstractControl} { return this.form.controls; }
addControl(dir: NgControl): Control { addControl(dir: NgControl): FormControl {
const ctrl = new Control(); const ctrl = new FormControl();
PromiseWrapper.scheduleMicrotask(() => { PromiseWrapper.scheduleMicrotask(() => {
const container = this._findContainer(dir.path); const container = this._findContainer(dir.path);
setUpControl(ctrl, dir); setUpControl(ctrl, dir);
@ -120,7 +120,7 @@ export class NgForm extends ControlContainer implements Form {
return ctrl; return ctrl;
} }
getControl(dir: NgControl): Control { return <Control>this.form.find(dir.path); } getControl(dir: NgControl): FormControl { return <FormControl>this.form.find(dir.path); }
removeControl(dir: NgControl): void { removeControl(dir: NgControl): void {
PromiseWrapper.scheduleMicrotask(() => { PromiseWrapper.scheduleMicrotask(() => {
@ -131,17 +131,17 @@ export class NgForm extends ControlContainer implements Form {
}); });
} }
addControlGroup(dir: NgControlGroup): void { addFormGroup(dir: NgControlGroup): void {
PromiseWrapper.scheduleMicrotask(() => { PromiseWrapper.scheduleMicrotask(() => {
var container = this._findContainer(dir.path); var container = this._findContainer(dir.path);
var group = new ControlGroup({}); var group = new FormGroup({});
setUpControlGroup(group, dir); setUpFormGroup(group, dir);
container.registerControl(dir.name, group); container.registerControl(dir.name, group);
group.updateValueAndValidity({emitEvent: false}); group.updateValueAndValidity({emitEvent: false});
}); });
} }
removeControlGroup(dir: NgControlGroup): void { removeFormGroup(dir: NgControlGroup): void {
PromiseWrapper.scheduleMicrotask(() => { PromiseWrapper.scheduleMicrotask(() => {
var container = this._findContainer(dir.path); var container = this._findContainer(dir.path);
if (isPresent(container)) { if (isPresent(container)) {
@ -150,13 +150,11 @@ export class NgForm extends ControlContainer implements Form {
}); });
} }
getControlGroup(dir: NgControlGroup): ControlGroup { getFormGroup(dir: NgControlGroup): FormGroup { return <FormGroup>this.form.find(dir.path); }
return <ControlGroup>this.form.find(dir.path);
}
updateModel(dir: NgControl, value: any): void { updateModel(dir: NgControl, value: any): void {
PromiseWrapper.scheduleMicrotask(() => { PromiseWrapper.scheduleMicrotask(() => {
var ctrl = <Control>this.form.find(dir.path); var ctrl = <FormControl>this.form.find(dir.path);
ctrl.updateValue(value); ctrl.updateValue(value);
}); });
} }
@ -168,8 +166,8 @@ export class NgForm extends ControlContainer implements Form {
} }
/** @internal */ /** @internal */
_findContainer(path: string[]): ControlGroup { _findContainer(path: string[]): FormGroup {
path.pop(); path.pop();
return ListWrapper.isEmpty(path) ? this.form : <ControlGroup>this.form.find(path); return ListWrapper.isEmpty(path) ? this.form : <FormGroup>this.form.find(path);
} }
} }

View File

@ -2,7 +2,7 @@ import {Directive, Inject, OnChanges, Optional, Self, SimpleChanges, forwardRef}
import {EventEmitter, ObservableWrapper} from '../../facade/async'; import {EventEmitter, ObservableWrapper} from '../../facade/async';
import {StringMapWrapper} from '../../facade/collection'; import {StringMapWrapper} from '../../facade/collection';
import {Control} from '../model'; import {FormControl} from '../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators'; import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
@ -73,7 +73,7 @@ export const formControlBinding: any =
exportAs: 'ngForm' exportAs: 'ngForm'
}) })
export class NgFormControl extends NgControl implements OnChanges { export class NgFormControl extends NgControl implements OnChanges {
form: Control; form: FormControl;
update = new EventEmitter(); update = new EventEmitter();
model: any; model: any;
viewModel: any; viewModel: any;
@ -107,7 +107,7 @@ export class NgFormControl extends NgControl implements OnChanges {
return composeAsyncValidators(this._asyncValidators); return composeAsyncValidators(this._asyncValidators);
} }
get control(): Control { return this.form; } get control(): FormControl { return this.form; }
viewToModelUpdate(newValue: any): void { viewToModelUpdate(newValue: any): void {
this.viewModel = newValue; this.viewModel = newValue;

View File

@ -4,14 +4,14 @@ import {EventEmitter, ObservableWrapper} from '../../facade/async';
import {ListWrapper, StringMapWrapper} from '../../facade/collection'; import {ListWrapper, StringMapWrapper} from '../../facade/collection';
import {BaseException} from '../../facade/exceptions'; import {BaseException} from '../../facade/exceptions';
import {isBlank} from '../../facade/lang'; import {isBlank} from '../../facade/lang';
import {Control, ControlGroup} from '../model'; import {FormControl, FormGroup} from '../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS, Validators} from '../validators'; import {NG_ASYNC_VALIDATORS, NG_VALIDATORS, Validators} from '../validators';
import {ControlContainer} from './control_container'; import {ControlContainer} from './control_container';
import {Form} from './form_interface'; import {Form} from './form_interface';
import {NgControl} from './ng_control'; import {NgControl} from './ng_control';
import {NgControlGroup} from './ng_control_group'; import {NgControlGroup} from './ng_control_group';
import {composeAsyncValidators, composeValidators, setUpControl, setUpControlGroup} from './shared'; import {composeAsyncValidators, composeValidators, setUpControl, setUpFormGroup} from './shared';
export const formDirectiveProvider: any = export const formDirectiveProvider: any =
/*@ts2dart_const*/ /* @ts2dart_Provider */ { /*@ts2dart_const*/ /* @ts2dart_Provider */ {
@ -24,7 +24,7 @@ export const formDirectiveProvider: any =
* *
* ### Example ([live demo](http://plnkr.co/edit/jqrVirudY8anJxTMUjTP?p=preview)) * ### Example ([live demo](http://plnkr.co/edit/jqrVirudY8anJxTMUjTP?p=preview))
* *
* In this example, we bind the control group to the form element, and we bind the login and * In this example, we bind the form group to the form element, and we bind the login and
* password controls to the login and password elements. * password controls to the login and password elements.
* *
* ```typescript * ```typescript
@ -44,12 +44,12 @@ export const formDirectiveProvider: any =
* directives: [FORM_DIRECTIVES] * directives: [FORM_DIRECTIVES]
* }) * })
* export class App { * export class App {
* loginForm: ControlGroup; * loginForm: FormGroup;
* *
* constructor() { * constructor() {
* this.loginForm = new ControlGroup({ * this.loginForm = new FormGroup({
* login: new Control(""), * login: new FormControl(""),
* password: new Control("") * password: new FormControl("")
* }); * });
* } * }
* *
@ -75,12 +75,12 @@ export const formDirectiveProvider: any =
* }) * })
* class LoginComp { * class LoginComp {
* credentials: {login: string, password: string}; * credentials: {login: string, password: string};
* loginForm: ControlGroup; * loginForm: FormGroup;
* *
* constructor() { * constructor() {
* this.loginForm = new ControlGroup({ * this.loginForm = new FormGroup({
* login: new Control(""), * login: new FormControl(""),
* password: new Control("") * password: new FormControl("")
* }); * });
* } * }
* *
@ -105,7 +105,7 @@ export class NgFormModel extends ControlContainer implements Form,
OnChanges { OnChanges {
private _submitted: boolean = false; private _submitted: boolean = false;
form: ControlGroup = null; form: FormGroup = null;
directives: NgControl[] = []; directives: NgControl[] = [];
ngSubmit = new EventEmitter(); ngSubmit = new EventEmitter();
@ -134,11 +134,11 @@ export class NgFormModel extends ControlContainer implements Form,
get formDirective(): Form { return this; } get formDirective(): Form { return this; }
get control(): ControlGroup { return this.form; } get control(): FormGroup { return this.form; }
get path(): string[] { return []; } get path(): string[] { return []; }
addControl(dir: NgControl): Control { addControl(dir: NgControl): FormControl {
const ctrl: any = this.form.find(dir.path); const ctrl: any = this.form.find(dir.path);
setUpControl(ctrl, dir); setUpControl(ctrl, dir);
ctrl.updateValueAndValidity({emitEvent: false}); ctrl.updateValueAndValidity({emitEvent: false});
@ -146,24 +146,22 @@ export class NgFormModel extends ControlContainer implements Form,
return ctrl; return ctrl;
} }
getControl(dir: NgControl): Control { return <Control>this.form.find(dir.path); } getControl(dir: NgControl): FormControl { return <FormControl>this.form.find(dir.path); }
removeControl(dir: NgControl): void { ListWrapper.remove(this.directives, dir); } removeControl(dir: NgControl): void { ListWrapper.remove(this.directives, dir); }
addControlGroup(dir: NgControlGroup) { addFormGroup(dir: NgControlGroup) {
var ctrl: any = this.form.find(dir.path); var ctrl: any = this.form.find(dir.path);
setUpControlGroup(ctrl, dir); setUpFormGroup(ctrl, dir);
ctrl.updateValueAndValidity({emitEvent: false}); ctrl.updateValueAndValidity({emitEvent: false});
} }
removeControlGroup(dir: NgControlGroup) {} removeFormGroup(dir: NgControlGroup) {}
getControlGroup(dir: NgControlGroup): ControlGroup { getFormGroup(dir: NgControlGroup): FormGroup { return <FormGroup>this.form.find(dir.path); }
return <ControlGroup>this.form.find(dir.path);
}
updateModel(dir: NgControl, value: any): void { updateModel(dir: NgControl, value: any): void {
var ctrl  = <Control>this.form.find(dir.path); var ctrl  = <FormControl>this.form.find(dir.path);
ctrl.updateValue(value); ctrl.updateValue(value);
} }

View File

@ -2,7 +2,7 @@ import {Directive, Host, Inject, Input, OnChanges, OnDestroy, Optional, Output,
import {EventEmitter, ObservableWrapper} from '../../facade/async'; import {EventEmitter, ObservableWrapper} from '../../facade/async';
import {BaseException} from '../../facade/exceptions'; import {BaseException} from '../../facade/exceptions';
import {Control} from '../model'; import {FormControl} from '../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators'; import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';
import {ControlContainer} from './control_container'; import {ControlContainer} from './control_container';
@ -48,7 +48,7 @@ export const formControlBinding: any =
export class NgModel extends NgControl implements OnChanges, export class NgModel extends NgControl implements OnChanges,
OnDestroy { OnDestroy {
/** @internal */ /** @internal */
_control: Control; _control: FormControl;
/** @internal */ /** @internal */
_added = false; _added = false;
viewModel: any; viewModel: any;
@ -65,7 +65,7 @@ export class NgModel extends NgControl implements OnChanges,
valueAccessors: ControlValueAccessor[]) { valueAccessors: ControlValueAccessor[]) {
super(); super();
this.valueAccessor = selectValueAccessor(this, valueAccessors); this.valueAccessor = selectValueAccessor(this, valueAccessors);
if (!this._parent) this._control = new Control(); if (!this._parent) this._control = new FormControl();
} }
ngOnChanges(changes: SimpleChanges) { ngOnChanges(changes: SimpleChanges) {
@ -80,7 +80,7 @@ export class NgModel extends NgControl implements OnChanges,
ngOnDestroy(): void { this.formDirective && this.formDirective.removeControl(this); } ngOnDestroy(): void { this.formDirective && this.formDirective.removeControl(this); }
get control(): Control { return this._control; } get control(): FormControl { return this._control; }
get path(): string[] { get path(): string[] {
return this._parent ? controlPath(this.name, this._parent) : []; return this._parent ? controlPath(this.name, this._parent) : [];
@ -105,7 +105,7 @@ export class NgModel extends NgControl implements OnChanges,
this._added = true; this._added = true;
} }
private _addStandaloneControl(): Control { private _addStandaloneControl(): FormControl {
setUpControl(this._control, this); setUpControl(this._control, this);
this._control.updateValueAndValidity({emitEvent: false}); this._control.updateValueAndValidity({emitEvent: false});
return this._control; return this._control;

View File

@ -1,7 +1,7 @@
import {ListWrapper, StringMapWrapper} from '../../facade/collection'; import {ListWrapper, StringMapWrapper} from '../../facade/collection';
import {BaseException} from '../../facade/exceptions'; import {BaseException} from '../../facade/exceptions';
import {hasConstructor, isBlank, isPresent, looseIdentical} from '../../facade/lang'; import {hasConstructor, isBlank, isPresent, looseIdentical} from '../../facade/lang';
import {Control, ControlGroup} from '../model'; import {FormControl, FormGroup} from '../model';
import {Validators} from '../validators'; import {Validators} from '../validators';
import {AbstractControlDirective} from './abstract_control_directive'; import {AbstractControlDirective} from './abstract_control_directive';
@ -24,7 +24,7 @@ export function controlPath(name: string, parent: ControlContainer): string[] {
return p; return p;
} }
export function setUpControl(control: Control, dir: NgControl): void { export function setUpControl(control: FormControl, dir: NgControl): void {
if (isBlank(control)) _throwError(dir, 'Cannot find control'); if (isBlank(control)) _throwError(dir, 'Cannot find control');
if (isBlank(dir.valueAccessor)) _throwError(dir, 'No value accessor for'); if (isBlank(dir.valueAccessor)) _throwError(dir, 'No value accessor for');
@ -46,7 +46,7 @@ export function setUpControl(control: Control, dir: NgControl): void {
dir.valueAccessor.registerOnTouched(() => control.markAsTouched()); dir.valueAccessor.registerOnTouched(() => control.markAsTouched());
} }
export function setUpControlGroup(control: ControlGroup, dir: NgControlGroup) { export function setUpFormGroup(control: FormGroup, dir: NgControlGroup) {
if (isBlank(control)) _throwError(dir, 'Cannot find control'); if (isBlank(control)) _throwError(dir, 'Cannot find control');
control.validator = Validators.compose([control.validator, dir.validator]); control.validator = Validators.compose([control.validator, dir.validator]);
control.asyncValidator = Validators.composeAsync([control.asyncValidator, dir.asyncValidator]); control.asyncValidator = Validators.composeAsync([control.asyncValidator, dir.asyncValidator]);

View File

@ -31,7 +31,7 @@ import * as modelModule from './model';
* directives: [FORM_DIRECTIVES] * directives: [FORM_DIRECTIVES]
* }) * })
* export class App { * export class App {
* loginForm: ControlGroup; * loginForm: FormGroup;
* *
* constructor(builder: FormBuilder) { * constructor(builder: FormBuilder) {
* this.loginForm = builder.group({ * this.loginForm = builder.group({
@ -54,38 +54,38 @@ import * as modelModule from './model';
@Injectable() @Injectable()
export class FormBuilder { export class FormBuilder {
/** /**
* Construct a new {@link ControlGroup} with the given map of configuration. * Construct a new {@link FormGroup} with the given map of configuration.
* Valid keys for the `extra` parameter map are `optionals` and `validator`. * Valid keys for the `extra` parameter map are `optionals` and `validator`.
* *
* See the {@link ControlGroup} constructor for more details. * See the {@link FormGroup} constructor for more details.
*/ */
group(controlsConfig: {[key: string]: any}, extra: {[key: string]: any} = null): group(controlsConfig: {[key: string]: any}, extra: {[key: string]: any} = null):
modelModule.ControlGroup { modelModule.FormGroup {
var controls = this._reduceControls(controlsConfig); var controls = this._reduceControls(controlsConfig);
var optionals = <{[key: string]: boolean}>( var optionals = <{[key: string]: boolean}>(
isPresent(extra) ? StringMapWrapper.get(extra, 'optionals') : null); isPresent(extra) ? StringMapWrapper.get(extra, 'optionals') : null);
var validator: ValidatorFn = isPresent(extra) ? StringMapWrapper.get(extra, 'validator') : null; var validator: ValidatorFn = isPresent(extra) ? StringMapWrapper.get(extra, 'validator') : null;
var asyncValidator: AsyncValidatorFn = var asyncValidator: AsyncValidatorFn =
isPresent(extra) ? StringMapWrapper.get(extra, 'asyncValidator') : null; isPresent(extra) ? StringMapWrapper.get(extra, 'asyncValidator') : null;
return new modelModule.ControlGroup(controls, optionals, validator, asyncValidator); return new modelModule.FormGroup(controls, optionals, validator, asyncValidator);
} }
/** /**
* Construct a new {@link Control} with the given `value`,`validator`, and `asyncValidator`. * Construct a new {@link FormControl} with the given `value`,`validator`, and `asyncValidator`.
*/ */
control(value: Object, validator: ValidatorFn = null, asyncValidator: AsyncValidatorFn = null): control(value: Object, validator: ValidatorFn = null, asyncValidator: AsyncValidatorFn = null):
modelModule.Control { modelModule.FormControl {
return new modelModule.Control(value, validator, asyncValidator); return new modelModule.FormControl(value, validator, asyncValidator);
} }
/** /**
* Construct an array of {@link Control}s from the given `controlsConfig` array of * Construct an array of {@link FormControl}s from the given `controlsConfig` array of
* configuration, with the given optional `validator` and `asyncValidator`. * configuration, with the given optional `validator` and `asyncValidator`.
*/ */
array( array(
controlsConfig: any[], validator: ValidatorFn = null, controlsConfig: any[], validator: ValidatorFn = null,
asyncValidator: AsyncValidatorFn = null): modelModule.ControlArray { asyncValidator: AsyncValidatorFn = null): modelModule.FormArray {
var controls = controlsConfig.map(c => this._createControl(c)); var controls = controlsConfig.map(c => this._createControl(c));
return new modelModule.ControlArray(controls, validator, asyncValidator); return new modelModule.FormArray(controls, validator, asyncValidator);
} }
/** @internal */ /** @internal */
@ -100,9 +100,9 @@ export class FormBuilder {
/** @internal */ /** @internal */
_createControl(controlConfig: any): modelModule.AbstractControl { _createControl(controlConfig: any): modelModule.AbstractControl {
if (controlConfig instanceof modelModule.Control || if (controlConfig instanceof modelModule.FormControl ||
controlConfig instanceof modelModule.ControlGroup || controlConfig instanceof modelModule.FormGroup ||
controlConfig instanceof modelModule.ControlArray) { controlConfig instanceof modelModule.FormArray) {
return controlConfig; return controlConfig;
} else if (isArray(controlConfig)) { } else if (isArray(controlConfig)) {

View File

@ -7,17 +7,17 @@ import {AsyncValidatorFn, ValidatorFn} from './directives/validators';
/** /**
* Indicates that a Control is valid, i.e. that no errors exist in the input value. * Indicates that a FormControl is valid, i.e. that no errors exist in the input value.
*/ */
export const VALID = 'VALID'; export const VALID = 'VALID';
/** /**
* Indicates that a Control is invalid, i.e. that an error exists in the input value. * Indicates that a FormControl is invalid, i.e. that an error exists in the input value.
*/ */
export const INVALID = 'INVALID'; export const INVALID = 'INVALID';
/** /**
* Indicates that a Control is pending, i.e. that async validation is occurring and * Indicates that a FormControl is pending, i.e. that async validation is occurring and
* errors are not yet available for the input value. * errors are not yet available for the input value.
*/ */
export const PENDING = 'PENDING'; export const PENDING = 'PENDING';
@ -35,9 +35,9 @@ function _find(control: AbstractControl, path: Array<string|number>| string) {
if (path instanceof Array && ListWrapper.isEmpty(path)) return null; if (path instanceof Array && ListWrapper.isEmpty(path)) return null;
return (<Array<string|number>>path).reduce((v, name) => { return (<Array<string|number>>path).reduce((v, name) => {
if (v instanceof ControlGroup) { if (v instanceof FormGroup) {
return isPresent(v.controls[name]) ? v.controls[name] : null; return isPresent(v.controls[name]) ? v.controls[name] : null;
} else if (v instanceof ControlArray) { } else if (v instanceof FormArray) {
var index = <number>name; var index = <number>name;
return isPresent(v.at(index)) ? v.at(index) : null; return isPresent(v.at(index)) ? v.at(index) : null;
} else { } else {
@ -63,7 +63,7 @@ export abstract class AbstractControl {
private _errors: {[key: string]: any}; private _errors: {[key: string]: any};
private _pristine: boolean = true; private _pristine: boolean = true;
private _touched: boolean = false; private _touched: boolean = false;
private _parent: ControlGroup|ControlArray; private _parent: FormGroup|FormArray;
private _asyncValidationSubscription: any; private _asyncValidationSubscription: any;
constructor(public validator: ValidatorFn, public asyncValidator: AsyncValidatorFn) {} constructor(public validator: ValidatorFn, public asyncValidator: AsyncValidatorFn) {}
@ -113,7 +113,7 @@ export abstract class AbstractControl {
} }
} }
setParent(parent: ControlGroup|ControlArray): void { this._parent = parent; } setParent(parent: FormGroup|FormArray): void { this._parent = parent; }
updateValueAndValidity({onlySelf, emitEvent}: {onlySelf?: boolean, emitEvent?: boolean} = {}): updateValueAndValidity({onlySelf, emitEvent}: {onlySelf?: boolean, emitEvent?: boolean} = {}):
void { void {
@ -160,7 +160,7 @@ export abstract class AbstractControl {
} }
/** /**
* Sets errors on a control. * Sets errors on a form control.
* *
* This is used when validations are run not automatically, but manually by the user. * This is used when validations are run not automatically, but manually by the user.
* *
@ -169,7 +169,7 @@ export abstract class AbstractControl {
* ## Usage * ## Usage
* *
* ``` * ```
* var login = new Control("someLogin"); * var login = new FormControl("someLogin");
* login.setErrors({ * login.setErrors({
* "notUnique": true * "notUnique": true
* }); * });
@ -253,24 +253,26 @@ export abstract class AbstractControl {
} }
/** /**
* Defines a part of a form that cannot be divided into other controls. `Control`s have values and * Defines a part of a form that cannot be divided into other controls. `FormControl`s have values
* and
* validation state, which is determined by an optional validation function. * validation state, which is determined by an optional validation function.
* *
* `Control` is one of the three fundamental building blocks used to define forms in Angular, along * `FormControl` is one of the three fundamental building blocks used to define forms in Angular,
* with {@link ControlGroup} and {@link ControlArray}. * along
* with {@link FormGroup} and {@link FormArray}.
* *
* ## Usage * ## Usage
* *
* By default, a `Control` is created for every `<input>` or other form component. * By default, a `FormControl` is created for every `<input>` or other form component.
* With {@link NgFormControl} or {@link NgFormModel} an existing {@link Control} can be * With {@link NgFormControl} or {@link NgFormModel} an existing {@link FormControl} can be
* bound to a DOM element instead. This `Control` can be configured with a custom * bound to a DOM element instead. This `FormControl` can be configured with a custom
* validation function. * validation function.
* *
* ### Example ([live demo](http://plnkr.co/edit/23DESOpbNnBpBHZt1BR4?p=preview)) * ### Example ([live demo](http://plnkr.co/edit/23DESOpbNnBpBHZt1BR4?p=preview))
* *
* @experimental * @experimental
*/ */
export class Control extends AbstractControl { export class FormControl extends AbstractControl {
/** @internal */ /** @internal */
_onChange: Function; _onChange: Function;
@ -283,11 +285,11 @@ export class Control extends AbstractControl {
} }
/** /**
* Set the value of the control to `value`. * Set the value of the form control to `value`.
* *
* If `onlySelf` is `true`, this change will only affect the validation of this `Control` * If `onlySelf` is `true`, this change will only affect the validation of this `FormControl`
* and not its parent component. If `emitEvent` is `true`, this change will cause a * and not its parent component. If `emitEvent` is `true`, this change will cause a
* `valueChanges` event on the `Control` to be emitted. Both of these options default to * `valueChanges` event on the `FormControl` to be emitted. Both of these options default to
* `false`. * `false`.
* *
* If `emitModelToViewChange` is `true`, the view will be notified about the new value * If `emitModelToViewChange` is `true`, the view will be notified about the new value
@ -324,20 +326,20 @@ export class Control extends AbstractControl {
/** /**
* Defines a part of a form, of fixed length, that can contain other controls. * Defines a part of a form, of fixed length, that can contain other controls.
* *
* A `ControlGroup` aggregates the values of each {@link Control} in the group. * A `FormGroup` aggregates the values of each {@link FormControl} in the group.
* The status of a `ControlGroup` depends on the status of its children. * The status of a `FormGroup` depends on the status of its children.
* If one of the controls in a group is invalid, the entire group is invalid. * If one of the controls in a group is invalid, the entire group is invalid.
* Similarly, if a control changes its value, the entire group changes as well. * Similarly, if a control changes its value, the entire group changes as well.
* *
* `ControlGroup` is one of the three fundamental building blocks used to define forms in Angular, * `FormGroup` is one of the three fundamental building blocks used to define forms in Angular,
* along with {@link Control} and {@link ControlArray}. {@link ControlArray} can also contain other * along with {@link FormControl} and {@link FormArray}. {@link FormArray} can also contain other
* controls, but is of variable length. * controls, but is of variable length.
* *
* ### Example ([live demo](http://plnkr.co/edit/23DESOpbNnBpBHZt1BR4?p=preview)) * ### Example ([live demo](http://plnkr.co/edit/23DESOpbNnBpBHZt1BR4?p=preview))
* *
* @experimental * @experimental
*/ */
export class ControlGroup extends AbstractControl { export class FormGroup extends AbstractControl {
private _optionals: {[key: string]: boolean}; private _optionals: {[key: string]: boolean};
constructor( constructor(
@ -446,28 +448,28 @@ export class ControlGroup extends AbstractControl {
/** /**
* Defines a part of a form, of variable length, that can contain other controls. * Defines a part of a form, of variable length, that can contain other controls.
* *
* A `ControlArray` aggregates the values of each {@link Control} in the group. * A `FormArray` aggregates the values of each {@link FormControl} in the group.
* The status of a `ControlArray` depends on the status of its children. * The status of a `FormArray` depends on the status of its children.
* If one of the controls in a group is invalid, the entire array is invalid. * If one of the controls in a group is invalid, the entire array is invalid.
* Similarly, if a control changes its value, the entire array changes as well. * Similarly, if a control changes its value, the entire array changes as well.
* *
* `ControlArray` is one of the three fundamental building blocks used to define forms in Angular, * `FormArray` is one of the three fundamental building blocks used to define forms in Angular,
* along with {@link Control} and {@link ControlGroup}. {@link ControlGroup} can also contain * along with {@link FormControl} and {@link FormGroup}. {@link FormGroup} can also contain
* other controls, but is of fixed length. * other controls, but is of fixed length.
* *
* ## Adding or removing controls * ## Adding or removing controls
* *
* To change the controls in the array, use the `push`, `insert`, or `removeAt` methods * To change the controls in the array, use the `push`, `insert`, or `removeAt` methods
* in `ControlArray` itself. These methods ensure the controls are properly tracked in the * in `FormArray` itself. These methods ensure the controls are properly tracked in the
* form's hierarchy. Do not modify the array of `AbstractControl`s used to instantiate * form's hierarchy. Do not modify the array of `AbstractControl`s used to instantiate
* the `ControlArray` directly, as that will result in strange and unexpected behavior such * the `FormArray` directly, as that will result in strange and unexpected behavior such
* as broken change detection. * as broken change detection.
* *
* ### Example ([live demo](http://plnkr.co/edit/23DESOpbNnBpBHZt1BR4?p=preview)) * ### Example ([live demo](http://plnkr.co/edit/23DESOpbNnBpBHZt1BR4?p=preview))
* *
* @experimental * @experimental
*/ */
export class ControlArray extends AbstractControl { export class FormArray extends AbstractControl {
constructor( constructor(
public controls: AbstractControl[], validator: ValidatorFn = null, public controls: AbstractControl[], validator: ValidatorFn = null,
asyncValidator: AsyncValidatorFn = null) { asyncValidator: AsyncValidatorFn = null) {

View File

@ -10,7 +10,7 @@ import * as modelModule from './model';
/** /**
* Providers for validators to be used for {@link Control}s in a form. * Providers for validators to be used for {@link FormControl}s in a form.
* *
* Provide this using `multi: true` to add validators. * Provide this using `multi: true` to add validators.
* *
@ -22,7 +22,7 @@ import * as modelModule from './model';
export const NG_VALIDATORS: OpaqueToken = /*@ts2dart_const*/ new OpaqueToken('NgValidators'); export const NG_VALIDATORS: OpaqueToken = /*@ts2dart_const*/ new OpaqueToken('NgValidators');
/** /**
* Providers for asynchronous validators to be used for {@link Control}s * Providers for asynchronous validators to be used for {@link FormControl}s
* in a form. * in a form.
* *
* Provide this using `multi: true` to add validators. * Provide this using `multi: true` to add validators.
@ -37,13 +37,13 @@ export const NG_ASYNC_VALIDATORS: OpaqueToken =
/** /**
* Provides a set of validators used by form controls. * Provides a set of validators used by form controls.
* *
* A validator is a function that processes a {@link Control} or collection of * A validator is a function that processes a {@link FormControl} or collection of
* controls and returns a map of errors. A null map means that validation has passed. * controls and returns a map of errors. A null map means that validation has passed.
* *
* ### Example * ### Example
* *
* ```typescript * ```typescript
* var loginControl = new Control("", Validators.required) * var loginControl = new FormControl("", Validators.required)
* ``` * ```
* *
* @experimental * @experimental

View File

@ -1,4 +1,4 @@
import {Control, FormBuilder} from '@angular/common'; import {Control, FormBuilder} from '@angular/common/src/forms-deprecated';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal'; import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
import {PromiseWrapper} from '../../src/facade/promise'; import {PromiseWrapper} from '../../src/facade/promise';

View File

@ -1,4 +1,5 @@
import {Control, ControlGroup, ControlValueAccessor, FORM_DIRECTIVES, NG_ASYNC_VALIDATORS, NG_VALIDATORS, NgControl, NgFor, NgForm, NgIf, RadioButtonState, Validator, Validators} from '@angular/common'; import {NgFor, NgIf} from '@angular/common';
import {Control, ControlGroup, ControlValueAccessor, FORM_DIRECTIVES, FORM_PROVIDERS, NG_ASYNC_VALIDATORS, NG_VALIDATORS, NgControl, NgForm, RadioButtonState, Validator, Validators} from '@angular/common/src/forms-deprecated';
import {TestComponentBuilder} from '@angular/compiler/testing'; import {TestComponentBuilder} from '@angular/compiler/testing';
import {ComponentFixture} from '@angular/compiler/testing'; import {ComponentFixture} from '@angular/compiler/testing';
import {Component, Directive, EventEmitter, Output} from '@angular/core'; import {Component, Directive, EventEmitter, Output} from '@angular/core';
@ -1542,7 +1543,8 @@ class UniqLoginValidator implements Validator {
template: '', template: '',
directives: [ directives: [
FORM_DIRECTIVES, WrappedValue, MyInput, NgIf, NgFor, LoginIsEmptyValidator, UniqLoginValidator FORM_DIRECTIVES, WrappedValue, MyInput, NgIf, NgFor, LoginIsEmptyValidator, UniqLoginValidator
] ],
providers: [FORM_PROVIDERS]
}) })
class MyComp8 { class MyComp8 {
form: any; form: any;

View File

@ -1,7 +1,7 @@
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, inject,} from '@angular/core/testing/testing_internal'; import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, inject,} from '@angular/core/testing/testing_internal';
import {fakeAsync, flushMicrotasks, Log, tick} from '@angular/core/testing'; import {fakeAsync, flushMicrotasks, Log, tick} from '@angular/core/testing';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {ControlGroup, Control, ControlArray, Validators} from '@angular/common'; import {ControlGroup, Control, ControlArray, Validators} from '@angular/common/src/forms-deprecated';
import {IS_DART, isPresent} from '../../src/facade/lang'; import {IS_DART, isPresent} from '../../src/facade/lang';
import {PromiseWrapper} from '../../src/facade/promise'; import {PromiseWrapper} from '../../src/facade/promise';
import {TimerWrapper, ObservableWrapper, EventEmitter} from '../../src/facade/async'; import {TimerWrapper, ObservableWrapper, EventEmitter} from '../../src/facade/async';

View File

@ -1,4 +1,4 @@
import {AbstractControl, Control, ControlArray, ControlGroup, Validators} from '@angular/common'; import {AbstractControl, Control, ControlArray, ControlGroup, Validators} from '@angular/common/src/forms-deprecated';
import {Log, fakeAsync, flushMicrotasks, tick} from '@angular/core/testing'; import {Log, fakeAsync, flushMicrotasks, tick} from '@angular/core/testing';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal'; import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';

View File

@ -4,7 +4,7 @@ import {fakeAsync, flushMicrotasks, Log, tick,} from '@angular/core/testing';
import {SpyNgControl, SpyValueAccessor} from '../spies'; import {SpyNgControl, SpyValueAccessor} from '../spies';
import {ControlGroup, Control, NgControlName, NgControlGroup, NgFormModel, ControlValueAccessor, Validators, NgForm, NgModel, NgFormControl, NgControl, DefaultValueAccessor, CheckboxControlValueAccessor, SelectControlValueAccessor, Validator} from '@angular/common/src/forms'; import {FormGroup, FormControl, NgControlName, NgControlGroup, NgFormModel, ControlValueAccessor, Validators, NgForm, NgModel, NgFormControl, NgControl, DefaultValueAccessor, CheckboxControlValueAccessor, SelectControlValueAccessor, Validator} from '@angular/common/src/forms';
import {selectValueAccessor, composeValidators} from '@angular/common/src/forms/directives/shared'; import {selectValueAccessor, composeValidators} from '@angular/common/src/forms/directives/shared';
@ -22,7 +22,7 @@ class DummyControlValueAccessor implements ControlValueAccessor {
} }
class CustomValidatorDirective implements Validator { class CustomValidatorDirective implements Validator {
validate(c: Control): {[key: string]: any} { return {'custom': true}; } validate(c: FormControl): {[key: string]: any} { return {'custom': true}; }
} }
function asyncValidator(expected: any /** TODO #9100 */, timeout = 0) { function asyncValidator(expected: any /** TODO #9100 */, timeout = 0) {
@ -94,28 +94,28 @@ export function main() {
var dummy1 = (_: any /** TODO #9100 */) => ({'dummy1': true}); var dummy1 = (_: any /** TODO #9100 */) => ({'dummy1': true});
var dummy2 = (_: any /** TODO #9100 */) => ({'dummy2': true}); var dummy2 = (_: any /** TODO #9100 */) => ({'dummy2': true});
var v = composeValidators([dummy1, dummy2]); var v = composeValidators([dummy1, dummy2]);
expect(v(new Control(''))).toEqual({'dummy1': true, 'dummy2': true}); expect(v(new FormControl(''))).toEqual({'dummy1': true, 'dummy2': true});
}); });
it('should compose validator directives', () => { it('should compose validator directives', () => {
var dummy1 = (_: any /** TODO #9100 */) => ({'dummy1': true}); var dummy1 = (_: any /** TODO #9100 */) => ({'dummy1': true});
var v = composeValidators([dummy1, new CustomValidatorDirective()]); var v = composeValidators([dummy1, new CustomValidatorDirective()]);
expect(v(new Control(''))).toEqual({'dummy1': true, 'custom': true}); expect(v(new FormControl(''))).toEqual({'dummy1': true, 'custom': true});
}); });
}); });
}); });
describe('NgFormModel', () => { describe('NgFormModel', () => {
var form: any /** TODO #9100 */; var form: any /** TODO #9100 */;
var formModel: ControlGroup; var formModel: FormGroup;
var loginControlDir: any /** TODO #9100 */; var loginControlDir: any /** TODO #9100 */;
beforeEach(() => { beforeEach(() => {
form = new NgFormModel([], []); form = new NgFormModel([], []);
formModel = new ControlGroup({ formModel = new FormGroup({
'login': new Control(), 'login': new FormControl(),
'passwords': 'passwords': new FormGroup(
new ControlGroup({'password': new Control(), 'passwordConfirm': new Control()}) {'password': new FormControl(), 'passwordConfirm': new FormControl()})
}); });
form.form = formModel; form.form = formModel;
@ -160,7 +160,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);
(<Control>formModel.find(['login'])).updateValue('invalid value'); (<FormControl>formModel.find(['login'])).updateValue('invalid value');
// sync validator passes, running async validators // sync validator passes, running async validators
expect(formModel.pending).toBe(true); expect(formModel.pending).toBe(true);
@ -172,7 +172,7 @@ export function main() {
})); }));
it('should write value to the DOM', () => { it('should write value to the DOM', () => {
(<Control>formModel.find(['login'])).updateValue('initValue'); (<FormControl>formModel.find(['login'])).updateValue('initValue');
form.addControl(loginControlDir); form.addControl(loginControlDir);
@ -185,7 +185,7 @@ export function main() {
}); });
}); });
describe('addControlGroup', () => { describe('addFormGroup', () => {
var matchingPasswordsValidator = (g: any /** TODO #9100 */) => { var matchingPasswordsValidator = (g: any /** TODO #9100 */) => {
if (g.controls['password'].value != g.controls['passwordConfirm'].value) { if (g.controls['password'].value != g.controls['passwordConfirm'].value) {
return {'differentPasswords': true}; return {'differentPasswords': true};
@ -198,17 +198,17 @@ export function main() {
var group = new NgControlGroup( var group = new NgControlGroup(
form, [matchingPasswordsValidator], [asyncValidator('expected')]); form, [matchingPasswordsValidator], [asyncValidator('expected')]);
group.name = 'passwords'; group.name = 'passwords';
form.addControlGroup(group); form.addFormGroup(group);
(<Control>formModel.find(['passwords', 'password'])).updateValue('somePassword'); (<FormControl>formModel.find(['passwords', 'password'])).updateValue('somePassword');
(<Control>formModel.find([ (<FormControl>formModel.find([
'passwords', 'passwordConfirm' 'passwords', 'passwordConfirm'
])).updateValue('someOtherPassword'); ])).updateValue('someOtherPassword');
// sync validators are set // sync validators are set
expect(formModel.hasError('differentPasswords', ['passwords'])).toEqual(true); expect(formModel.hasError('differentPasswords', ['passwords'])).toEqual(true);
(<Control>formModel.find([ (<FormControl>formModel.find([
'passwords', 'passwordConfirm' 'passwords', 'passwordConfirm'
])).updateValue('somePassword'); ])).updateValue('somePassword');
@ -233,7 +233,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);
(<Control>formModel.find(['login'])).updateValue('new value'); (<FormControl>formModel.find(['login'])).updateValue('new value');
form.ngOnChanges({}); form.ngOnChanges({});
@ -263,7 +263,7 @@ export function main() {
describe('NgForm', () => { describe('NgForm', () => {
var form: any /** TODO #9100 */; var form: any /** TODO #9100 */;
var formModel: ControlGroup; var formModel: FormGroup;
var loginControlDir: any /** TODO #9100 */; var loginControlDir: any /** TODO #9100 */;
var personControlGroupDir: any /** TODO #9100 */; var personControlGroupDir: any /** TODO #9100 */;
@ -290,9 +290,9 @@ export function main() {
expect(form.untouched).toBe(formModel.untouched); expect(form.untouched).toBe(formModel.untouched);
}); });
describe('addControl & addControlGroup', () => { describe('addControl & addFormGroup', () => {
it('should create a control with the given name', fakeAsync(() => { it('should create a control with the given name', fakeAsync(() => {
form.addControlGroup(personControlGroupDir); form.addFormGroup(personControlGroupDir);
form.addControl(loginControlDir); form.addControl(loginControlDir);
flushMicrotasks(); flushMicrotasks();
@ -303,12 +303,12 @@ export function main() {
// should update the form's value and validity // should update the form's value and validity
}); });
describe('removeControl & removeControlGroup', () => { describe('removeControl & removeFormGroup', () => {
it('should remove control', fakeAsync(() => { it('should remove control', fakeAsync(() => {
form.addControlGroup(personControlGroupDir); form.addFormGroup(personControlGroupDir);
form.addControl(loginControlDir); form.addControl(loginControlDir);
form.removeControlGroup(personControlGroupDir); form.removeFormGroup(personControlGroupDir);
form.removeControl(loginControlDir); form.removeControl(loginControlDir);
flushMicrotasks(); flushMicrotasks();
@ -343,10 +343,10 @@ export function main() {
var controlGroupDir: any /** TODO #9100 */; var controlGroupDir: any /** TODO #9100 */;
beforeEach(() => { beforeEach(() => {
formModel = new ControlGroup({'login': new Control(null)}); formModel = new FormGroup({'login': new FormControl(null)});
var parent = new NgFormModel([], []); var parent = new NgFormModel([], []);
parent.form = new ControlGroup({'group': formModel}); parent.form = new FormGroup({'group': formModel});
controlGroupDir = new NgControlGroup(parent, [], []); controlGroupDir = new NgControlGroup(parent, [], []);
controlGroupDir.name = 'group'; controlGroupDir.name = 'group';
}); });
@ -381,14 +381,14 @@ export function main() {
controlDir = new NgFormControl([Validators.required], [], [defaultAccessor]); controlDir = new NgFormControl([Validators.required], [], [defaultAccessor]);
controlDir.valueAccessor = new DummyControlValueAccessor(); controlDir.valueAccessor = new DummyControlValueAccessor();
control = new Control(null); control = new FormControl(null);
controlDir.form = control; controlDir.form = control;
}); });
it('should reexport control properties', () => { checkProperties(control); }); it('should reexport control properties', () => { checkProperties(control); });
it('should reexport new control properties', () => { it('should reexport new control properties', () => {
var newControl = new Control(null); var newControl = new FormControl(null);
controlDir.form = newControl; controlDir.form = newControl;
controlDir.ngOnChanges({'form': new SimpleChange(control, newControl)}); controlDir.ngOnChanges({'form': new SimpleChange(control, newControl)});
@ -445,10 +445,10 @@ export function main() {
var controlNameDir: any /** TODO #9100 */; var controlNameDir: any /** TODO #9100 */;
beforeEach(() => { beforeEach(() => {
formModel = new Control('name'); formModel = new FormControl('name');
var parent = new NgFormModel([], []); var parent = new NgFormModel([], []);
parent.form = new ControlGroup({'name': formModel}); parent.form = new FormGroup({'name': formModel});
controlNameDir = new NgControlName(parent, [], [], [defaultAccessor]); controlNameDir = new NgControlName(parent, [], [], [defaultAccessor]);
controlNameDir.name = 'name'; controlNameDir.name = 'name';
}); });

View File

@ -1,4 +1,4 @@
import {Control, FormBuilder} from '@angular/common'; import {FormBuilder, FormControl} from '@angular/common/src/forms';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal'; import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
import {PromiseWrapper} from '../../src/facade/promise'; import {PromiseWrapper} from '../../src/facade/promise';

View File

@ -1,5 +1,5 @@
import {NgFor, NgIf} from '@angular/common'; import {NgFor, NgIf} from '@angular/common';
import {Control, ControlGroup, ControlValueAccessor, FORM_DIRECTIVES, FORM_PROVIDERS, NG_ASYNC_VALIDATORS, NG_VALIDATORS, NgControl, NgForm, NgModel, RadioButtonState, Validator, Validators} from '@angular/common/src/forms'; import {ControlValueAccessor, FORM_DIRECTIVES, FORM_PROVIDERS, FormControl, FormGroup, NG_ASYNC_VALIDATORS, NG_VALIDATORS, NgControl, NgForm, NgModel, RadioButtonState, Validator, Validators} from '@angular/common/src/forms';
import {TestComponentBuilder} from '@angular/compiler/testing'; import {TestComponentBuilder} from '@angular/compiler/testing';
import {ComponentFixture} from '@angular/compiler/testing'; import {ComponentFixture} from '@angular/compiler/testing';
import {Component, Directive, EventEmitter, Output} from '@angular/core'; import {Component, Directive, EventEmitter, Output} from '@angular/core';
@ -28,7 +28,7 @@ export function main() {
tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => { tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => {
fixture.debugElement.componentInstance.form = fixture.debugElement.componentInstance.form =
new ControlGroup({'login': new Control('loginValue')}); new FormGroup({'login': new FormControl('loginValue')});
fixture.detectChanges(); fixture.detectChanges();
var input = fixture.debugElement.query(By.css('input')); var input = fixture.debugElement.query(By.css('input'));
@ -56,7 +56,7 @@ export function main() {
inject( inject(
[TestComponentBuilder, AsyncTestCompleter], [TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => { (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var form = new ControlGroup({'login': new Control('oldValue')}); var form = new FormGroup({'login': new FormControl('oldValue')});
var t = `<div [ngFormModel]="form"> var t = `<div [ngFormModel]="form">
<input type="text" ngControl="login"> <input type="text" ngControl="login">
@ -79,7 +79,7 @@ export function main() {
inject( inject(
[TestComponentBuilder, AsyncTestCompleter], [TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => { (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var form = new ControlGroup({'login': new Control('oldValue')}); var form = new FormGroup({'login': new FormControl('oldValue')});
var t = `<div [ngFormModel]="form"> var t = `<div [ngFormModel]="form">
<input type="text" ngControl="login"> <input type="text" ngControl="login">
@ -110,7 +110,7 @@ export function main() {
let fixture = tcb.overrideTemplate(MyComp8, t).createFakeAsync(MyComp8); let fixture = tcb.overrideTemplate(MyComp8, t).createFakeAsync(MyComp8);
tick(); tick();
fixture.debugElement.componentInstance.form = new ControlGroup({}); fixture.debugElement.componentInstance.form = new FormGroup({});
fixture.debugElement.componentInstance.name = 'old'; fixture.debugElement.componentInstance.name = 'old';
tick(); tick();
@ -161,7 +161,7 @@ export function main() {
}); });
tick(); tick();
fixture.debugElement.componentInstance.form = new ControlGroup({}); fixture.debugElement.componentInstance.form = new FormGroup({});
fixture.debugElement.componentInstance.data = false; fixture.debugElement.componentInstance.data = false;
tick(); tick();
@ -177,7 +177,7 @@ export function main() {
inject( inject(
[TestComponentBuilder, AsyncTestCompleter], [TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => { (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var control = new Control('loginValue'); var control = new FormControl('loginValue');
var t = `<div><input type="text" [ngFormControl]="form"></div>`; var t = `<div><input type="text" [ngFormControl]="form"></div>`;
@ -206,11 +206,11 @@ export function main() {
tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => { tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => {
fixture.debugElement.componentInstance.form = fixture.debugElement.componentInstance.form =
new ControlGroup({'login': new Control('oldValue')}); new FormGroup({'login': new FormControl('oldValue')});
fixture.detectChanges(); fixture.detectChanges();
fixture.debugElement.componentInstance.form = fixture.debugElement.componentInstance.form =
new ControlGroup({'login': new Control('newValue')}); new FormGroup({'login': new FormControl('newValue')});
fixture.detectChanges(); fixture.detectChanges();
var input = fixture.debugElement.query(By.css('input')); var input = fixture.debugElement.query(By.css('input'));
@ -223,8 +223,8 @@ export function main() {
inject( inject(
[TestComponentBuilder, AsyncTestCompleter], [TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => { (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var login = new Control('oldValue'); var login = new FormControl('oldValue');
var form = new ControlGroup({'login': login}); var form = new FormGroup({'login': login});
var t = `<div [ngFormModel]="form"> var t = `<div [ngFormModel]="form">
<input type="text" ngControl="login"> <input type="text" ngControl="login">
@ -248,8 +248,8 @@ export function main() {
inject( inject(
[TestComponentBuilder, AsyncTestCompleter], [TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => { (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var login = new Control('oldValue'); var login = new FormControl('oldValue');
var form = new ControlGroup({'login': login}); var form = new FormGroup({'login': login});
var t = `<div [ngFormModel]="form"> var t = `<div [ngFormModel]="form">
<input type="text" ngControl="login"> <input type="text" ngControl="login">
@ -281,7 +281,7 @@ export function main() {
tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => { tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => {
fixture.debugElement.componentInstance.form = fixture.debugElement.componentInstance.form =
new ControlGroup({'text': new Control('old')}); new FormGroup({'text': new FormControl('old')});
fixture.detectChanges(); fixture.detectChanges();
var input = fixture.debugElement.query(By.css('input')); var input = fixture.debugElement.query(By.css('input'));
@ -305,7 +305,7 @@ export function main() {
tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => { tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => {
fixture.debugElement.componentInstance.form = fixture.debugElement.componentInstance.form =
new ControlGroup({'text': new Control('old')}); new FormGroup({'text': new FormControl('old')});
fixture.detectChanges(); fixture.detectChanges();
var input = fixture.debugElement.query(By.css('input')); var input = fixture.debugElement.query(By.css('input'));
expect(input.nativeElement.value).toEqual('old'); expect(input.nativeElement.value).toEqual('old');
@ -328,7 +328,7 @@ export function main() {
tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => { tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => {
fixture.debugElement.componentInstance.form = fixture.debugElement.componentInstance.form =
new ControlGroup({'text': new Control('old')}); new FormGroup({'text': new FormControl('old')});
fixture.detectChanges(); fixture.detectChanges();
var textarea = fixture.debugElement.query(By.css('textarea')); var textarea = fixture.debugElement.query(By.css('textarea'));
@ -352,7 +352,7 @@ export function main() {
tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => { tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => {
fixture.debugElement.componentInstance.form = fixture.debugElement.componentInstance.form =
new ControlGroup({'checkbox': new Control(true)}); new FormGroup({'checkbox': new FormControl(true)});
fixture.detectChanges(); fixture.detectChanges();
var input = fixture.debugElement.query(By.css('input')); var input = fixture.debugElement.query(By.css('input'));
@ -378,7 +378,7 @@ export function main() {
tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => { tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => {
fixture.debugElement.componentInstance.form = fixture.debugElement.componentInstance.form =
new ControlGroup({'num': new Control(10)}); new FormGroup({'num': new FormControl(10)});
fixture.detectChanges(); fixture.detectChanges();
var input = fixture.debugElement.query(By.css('input')); var input = fixture.debugElement.query(By.css('input'));
@ -402,7 +402,7 @@ export function main() {
tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => { tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => {
fixture.debugElement.componentInstance.form = fixture.debugElement.componentInstance.form =
new ControlGroup({'num': new Control(10)}); new FormGroup({'num': new FormControl(10)});
fixture.detectChanges(); fixture.detectChanges();
var input = fixture.debugElement.query(By.css('input')); var input = fixture.debugElement.query(By.css('input'));
@ -426,7 +426,7 @@ export function main() {
inject( inject(
[TestComponentBuilder, AsyncTestCompleter], [TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => { (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var form = new ControlGroup({'num': new Control(10)}); var form = new FormGroup({'num': new FormControl(10)});
var t = `<div [ngFormModel]="form"> var t = `<div [ngFormModel]="form">
<input type="number" ngControl="num" [(ngModel)]="data"> <input type="number" ngControl="num" [(ngModel)]="data">
</div>`; </div>`;
@ -453,9 +453,9 @@ export function main() {
</form>`; </form>`;
tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => { tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => {
fixture.debugElement.componentInstance.form = new ControlGroup({ fixture.debugElement.componentInstance.form = new FormGroup({
'foodChicken': new Control(new RadioButtonState(false, 'chicken')), 'foodChicken': new FormControl(new RadioButtonState(false, 'chicken')),
'foodFish': new Control(new RadioButtonState(true, 'fish')) 'foodFish': new FormControl(new RadioButtonState(true, 'fish'))
}); });
fixture.detectChanges(); fixture.detectChanges();
@ -532,7 +532,7 @@ export function main() {
tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => { tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => {
fixture.debugElement.componentInstance.form = fixture.debugElement.componentInstance.form =
new ControlGroup({'city': new Control('SF')}); new FormGroup({'city': new FormControl('SF')});
fixture.detectChanges(); fixture.detectChanges();
var select = fixture.debugElement.query(By.css('select')); var select = fixture.debugElement.query(By.css('select'));
@ -568,7 +568,7 @@ export function main() {
tick(); tick();
fixture.debugElement.componentInstance.form = fixture.debugElement.componentInstance.form =
new ControlGroup({'city': new Control('NYC')}); new FormGroup({'city': new FormControl('NYC')});
fixture.debugElement.componentInstance.data = ['SF', 'NYC']; fixture.debugElement.componentInstance.data = ['SF', 'NYC'];
fixture.detectChanges(); fixture.detectChanges();
@ -800,7 +800,7 @@ export function main() {
tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => { tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => {
fixture.debugElement.componentInstance.form = fixture.debugElement.componentInstance.form =
new ControlGroup({'name': new Control('aa')}); new FormGroup({'name': new FormControl('aa')});
fixture.detectChanges(); fixture.detectChanges();
var input = fixture.debugElement.query(By.css('input')); var input = fixture.debugElement.query(By.css('input'));
expect(input.nativeElement.value).toEqual('!aa!'); expect(input.nativeElement.value).toEqual('!aa!');
@ -824,7 +824,7 @@ export function main() {
tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => { tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((fixture) => {
fixture.debugElement.componentInstance.form = fixture.debugElement.componentInstance.form =
new ControlGroup({'name': new Control('aa')}); new FormGroup({'name': new FormControl('aa')});
fixture.detectChanges(); fixture.detectChanges();
var input = fixture.debugElement.query(By.css('my-input')); var input = fixture.debugElement.query(By.css('my-input'));
expect(input.componentInstance.value).toEqual('!aa!'); expect(input.componentInstance.value).toEqual('!aa!');
@ -847,8 +847,11 @@ export function main() {
inject( inject(
[TestComponentBuilder, AsyncTestCompleter], [TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => { (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var form = new ControlGroup( var form = new FormGroup({
{'login': new Control(''), 'min': new Control(''), 'max': new Control('')}); 'login': new FormControl(''),
'min': new FormControl(''),
'max': new FormControl('')
});
var t = `<div [ngFormModel]="form" login-is-empty-validator> var t = `<div [ngFormModel]="form" login-is-empty-validator>
<input type="text" ngControl="login" required> <input type="text" ngControl="login" required>
@ -892,7 +895,7 @@ export function main() {
it('should use async validators defined in the html', it('should use async validators defined in the html',
fakeAsync(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => { fakeAsync(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
var form = new ControlGroup({'login': new Control('')}); var form = new FormGroup({'login': new FormControl('')});
var t = `<div [ngFormModel]="form"> var t = `<div [ngFormModel]="form">
<input type="text" ngControl="login" uniq-login-validator="expected"> <input type="text" ngControl="login" uniq-login-validator="expected">
@ -923,7 +926,7 @@ export function main() {
inject( inject(
[TestComponentBuilder, AsyncTestCompleter], [TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => { (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var form = new ControlGroup({'login': new Control('aa', Validators.required)}); var form = new FormGroup({'login': new FormControl('aa', Validators.required)});
var t = `<div [ngFormModel]="form"> var t = `<div [ngFormModel]="form">
<input type="text" ngControl="login"> <input type="text" ngControl="login">
@ -946,8 +949,9 @@ export function main() {
it('should use async validators defined in the model', it('should use async validators defined in the model',
fakeAsync(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => { fakeAsync(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
var control = new Control('', Validators.required, uniqLoginAsyncValidator('expected')); var control =
var form = new ControlGroup({'login': control}); new FormControl('', Validators.required, uniqLoginAsyncValidator('expected'));
var form = new FormGroup({'login': control});
var t = `<div [ngFormModel]="form"> var t = `<div [ngFormModel]="form">
<input type="text" ngControl="login"> <input type="text" ngControl="login">
@ -985,7 +989,7 @@ export function main() {
[TestComponentBuilder, AsyncTestCompleter], [TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => { (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var form = var form =
new ControlGroup({'nested': new ControlGroup({'login': new Control('value')})}); new FormGroup({'nested': new FormGroup({'login': new FormControl('value')})});
var t = `<div [ngFormModel]="form"> var t = `<div [ngFormModel]="form">
<div ngControlGroup="nested"> <div ngControlGroup="nested">
@ -1008,7 +1012,7 @@ export function main() {
[TestComponentBuilder, AsyncTestCompleter], [TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => { (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var form = var form =
new ControlGroup({'nested': new ControlGroup({'login': new Control('value')})}); new FormGroup({'nested': new FormGroup({'login': new FormControl('value')})});
var t = `<div [ngFormModel]="form"> var t = `<div [ngFormModel]="form">
<div ngControlGroup="nested"> <div ngControlGroup="nested">
@ -1032,7 +1036,7 @@ export function main() {
it('should support ngModel for complex forms', it('should support ngModel for complex forms',
fakeAsync(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => { fakeAsync(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
var form = new ControlGroup({'name': new Control('')}); var form = new FormGroup({'name': new FormControl('')});
var t = var t =
`<div [ngFormModel]="form"><input type="text" ngControl="name" [(ngModel)]="name"></div>`; `<div [ngFormModel]="form"><input type="text" ngControl="name" [(ngModel)]="name"></div>`;
@ -1056,7 +1060,7 @@ export function main() {
it('should support ngModel for single fields', it('should support ngModel for single fields',
fakeAsync(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => { fakeAsync(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
var form = new Control(''); var form = new FormControl('');
var t = `<div><input type="text" [ngFormControl]="form" [(ngModel)]="name"></div>`; var t = `<div><input type="text" [ngFormControl]="form" [(ngModel)]="name"></div>`;
@ -1335,7 +1339,7 @@ export function main() {
inject( inject(
[TestComponentBuilder, AsyncTestCompleter], [TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => { (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var form = new Control('', Validators.required); var form = new FormControl('', Validators.required);
var t = `<div><input type="text" [ngFormControl]="form"></div>`; var t = `<div><input type="text" [ngFormControl]="form"></div>`;
@ -1368,7 +1372,7 @@ export function main() {
inject( inject(
[TestComponentBuilder, AsyncTestCompleter], [TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => { (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var form = new ControlGroup({'name': new Control('', Validators.required)}); var form = new FormGroup({'name': new FormControl('', Validators.required)});
var t = `<form [ngFormModel]="form"><input type="text" ngControl="name"></form>`; var t = `<form [ngFormModel]="form"><input type="text" ngControl="name"></form>`;
@ -1432,7 +1436,7 @@ export function main() {
describe('ngModel corner cases', () => { describe('ngModel corner cases', () => {
it('should not update the view when the value initially came from the view', it('should not update the view when the value initially came from the view',
fakeAsync(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => { fakeAsync(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
var form = new Control(''); var form = new FormControl('');
var t = `<div><input type="text" [ngFormControl]="form" [(ngModel)]="name"></div>`; var t = `<div><input type="text" [ngFormControl]="form" [(ngModel)]="name"></div>`;
let fixture = tcb.overrideTemplate(MyComp8, t).createFakeAsync(MyComp8); let fixture = tcb.overrideTemplate(MyComp8, t).createFakeAsync(MyComp8);
@ -1544,7 +1548,7 @@ function uniqLoginAsyncValidator(expectedValue: string) {
}; };
} }
function loginIsEmptyGroupValidator(c: ControlGroup) { function loginIsEmptyGroupValidator(c: FormGroup) {
return c.controls['login'].value == '' ? {'loginIsEmpty': true} : null; return c.controls['login'].value == '' ? {'loginIsEmpty': true} : null;
} }

View File

@ -1,7 +1,7 @@
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, inject,} from '@angular/core/testing/testing_internal'; import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, inject,} from '@angular/core/testing/testing_internal';
import {fakeAsync, flushMicrotasks, Log, tick} from '@angular/core/testing'; import {fakeAsync, flushMicrotasks, Log, tick} from '@angular/core/testing';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {ControlGroup, Control, ControlArray, Validators} from '@angular/common'; import {FormGroup, FormControl, FormArray, Validators} from '@angular/common/src/forms';
import {IS_DART, isPresent} from '../../src/facade/lang'; import {IS_DART, isPresent} from '../../src/facade/lang';
import {PromiseWrapper} from '../../src/facade/promise'; import {PromiseWrapper} from '../../src/facade/promise';
import {TimerWrapper, ObservableWrapper, EventEmitter} from '../../src/facade/async'; import {TimerWrapper, ObservableWrapper, EventEmitter} from '../../src/facade/async';
@ -32,33 +32,33 @@ export function main() {
} }
describe('Form Model', () => { describe('Form Model', () => {
describe('Control', () => { describe('FormControl', () => {
it('should default the value to null', () => { it('should default the value to null', () => {
var c = new Control(); var c = new FormControl();
expect(c.value).toBe(null); expect(c.value).toBe(null);
}); });
describe('validator', () => { describe('validator', () => {
it('should run validator with the initial value', () => { it('should run validator with the initial value', () => {
var c = new Control('value', Validators.required); var c = new FormControl('value', Validators.required);
expect(c.valid).toEqual(true); expect(c.valid).toEqual(true);
}); });
it('should rerun the validator when the value changes', () => { it('should rerun the validator when the value changes', () => {
var c = new Control('value', Validators.required); var c = new FormControl('value', Validators.required);
c.updateValue(null); c.updateValue(null);
expect(c.valid).toEqual(false); expect(c.valid).toEqual(false);
}); });
it('should return errors', () => { it('should return errors', () => {
var c = new Control(null, Validators.required); var c = new FormControl(null, Validators.required);
expect(c.errors).toEqual({'required': true}); expect(c.errors).toEqual({'required': true});
}); });
}); });
describe('asyncValidator', () => { describe('asyncValidator', () => {
it('should run validator with the initial value', fakeAsync(() => { it('should run validator with the initial value', fakeAsync(() => {
var c = new Control('value', null, asyncValidator('expected')); var c = new FormControl('value', null, asyncValidator('expected'));
tick(); tick();
expect(c.valid).toEqual(false); expect(c.valid).toEqual(false);
@ -66,7 +66,7 @@ export function main() {
})); }));
it('should support validators returning observables', fakeAsync(() => { it('should support validators returning observables', fakeAsync(() => {
var c = new Control('value', null, asyncValidatorReturningObservable); var c = new FormControl('value', null, asyncValidatorReturningObservable);
tick(); tick();
expect(c.valid).toEqual(false); expect(c.valid).toEqual(false);
@ -74,7 +74,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 Control('value', null, asyncValidator('expected')); var c = new FormControl('value', null, asyncValidator('expected'));
c.updateValue('expected'); c.updateValue('expected');
tick(); tick();
@ -83,7 +83,7 @@ export function main() {
})); }));
it('should run the async validator only when the sync validator passes', fakeAsync(() => { it('should run the async validator only when the sync validator passes', fakeAsync(() => {
var c = new Control('', Validators.required, asyncValidator('expected')); var c = new FormControl('', Validators.required, asyncValidator('expected'));
tick(); tick();
expect(c.errors).toEqual({'required': true}); expect(c.errors).toEqual({'required': true});
@ -96,7 +96,7 @@ export function main() {
it('should mark the control as pending while running the async validation', it('should mark the control as pending while running the async validation',
fakeAsync(() => { fakeAsync(() => {
var c = new Control('', null, asyncValidator('expected')); var c = new FormControl('', null, asyncValidator('expected'));
expect(c.pending).toEqual(true); expect(c.pending).toEqual(true);
@ -106,8 +106,8 @@ export function main() {
})); }));
it('should only use the latest async validation run', fakeAsync(() => { it('should only use the latest async validation run', fakeAsync(() => {
var c = var c = new FormControl(
new Control('', null, asyncValidator('expected', {'long': 200, 'expected': 100})); '', null, asyncValidator('expected', {'long': 200, 'expected': 100}));
c.updateValue('long'); c.updateValue('long');
c.updateValue('expected'); c.updateValue('expected');
@ -120,12 +120,12 @@ export function main() {
describe('dirty', () => { describe('dirty', () => {
it('should be false after creating a control', () => { it('should be false after creating a control', () => {
var c = new Control('value'); var c = new FormControl('value');
expect(c.dirty).toEqual(false); expect(c.dirty).toEqual(false);
}); });
it('should be true after changing the value of the control', () => { it('should be true after changing the value of the control', () => {
var c = new Control('value'); var c = new FormControl('value');
c.markAsDirty(); c.markAsDirty();
expect(c.dirty).toEqual(true); expect(c.dirty).toEqual(true);
}); });
@ -134,8 +134,8 @@ export function main() {
describe('updateValue', () => { describe('updateValue', () => {
var g: any /** TODO #9100 */, c: any /** TODO #9100 */; var g: any /** TODO #9100 */, c: any /** TODO #9100 */;
beforeEach(() => { beforeEach(() => {
c = new Control('oldValue'); c = new FormControl('oldValue');
g = new ControlGroup({'one': c}); g = new FormGroup({'one': c});
}); });
it('should update the value of the control', () => { it('should update the value of the control', () => {
@ -191,7 +191,7 @@ export function main() {
describe('valueChanges & statusChanges', () => { describe('valueChanges & statusChanges', () => {
var c: any /** TODO #9100 */; var c: any /** TODO #9100 */;
beforeEach(() => { c = new Control('old', Validators.required); }); beforeEach(() => { c = new FormControl('old', Validators.required); });
it('should fire an event after the value has been updated', it('should fire an event after the value has been updated',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
@ -214,7 +214,7 @@ export function main() {
})); }));
it('should fire an event after the status has been updated to pending', fakeAsync(() => { it('should fire an event after the status has been updated to pending', fakeAsync(() => {
var c = new Control('old', Validators.required, asyncValidator('expected')); var c = new FormControl('old', Validators.required, asyncValidator('expected'));
var log: any[] /** TODO #9100 */ = []; var log: any[] /** TODO #9100 */ = [];
ObservableWrapper.subscribe(c.valueChanges, (value) => log.push(`value: '${value}'`)); ObservableWrapper.subscribe(c.valueChanges, (value) => log.push(`value: '${value}'`));
@ -269,7 +269,7 @@ export function main() {
describe('setErrors', () => { describe('setErrors', () => {
it('should set errors on a control', () => { it('should set errors on a control', () => {
var c = new Control('someValue'); var c = new FormControl('someValue');
c.setErrors({'someError': true}); c.setErrors({'someError': true});
@ -278,7 +278,7 @@ export function main() {
}); });
it('should reset the errors and validity when the value changes', () => { it('should reset the errors and validity when the value changes', () => {
var c = new Control('someValue', Validators.required); var c = new FormControl('someValue', Validators.required);
c.setErrors({'someError': true}); c.setErrors({'someError': true});
c.updateValue(''); c.updateValue('');
@ -287,8 +287,8 @@ export function main() {
}); });
it('should update the parent group\'s validity', () => { it('should update the parent group\'s validity', () => {
var c = new Control('someValue'); var c = new FormControl('someValue');
var g = new ControlGroup({'one': c}); var g = new FormGroup({'one': c});
expect(g.valid).toEqual(true); expect(g.valid).toEqual(true);
@ -298,8 +298,8 @@ export function main() {
}); });
it('should not reset parent\'s errors', () => { it('should not reset parent\'s errors', () => {
var c = new Control('someValue'); var c = new FormControl('someValue');
var g = new ControlGroup({'one': c}); var g = new FormGroup({'one': c});
g.setErrors({'someGroupError': true}); g.setErrors({'someGroupError': true});
c.setErrors({'someError': true}); c.setErrors({'someError': true});
@ -308,8 +308,8 @@ export function main() {
}); });
it('should reset errors when updating a value', () => { it('should reset errors when updating a value', () => {
var c = new Control('oldValue'); var c = new FormControl('oldValue');
var g = new ControlGroup({'one': c}); var g = new FormGroup({'one': c});
g.setErrors({'someGroupError': true}); g.setErrors({'someGroupError': true});
c.setErrors({'someError': true}); c.setErrors({'someError': true});
@ -322,24 +322,26 @@ export function main() {
}); });
}); });
describe('ControlGroup', () => { describe('FormGroup', () => {
describe('value', () => { describe('value', () => {
it('should be the reduced value of the child controls', () => { it('should be the reduced value of the child controls', () => {
var g = new ControlGroup({'one': new Control('111'), 'two': new Control('222')}); var g = new FormGroup({'one': new FormControl('111'), 'two': new FormControl('222')});
expect(g.value).toEqual({'one': '111', 'two': '222'}); expect(g.value).toEqual({'one': '111', 'two': '222'});
}); });
it('should be empty when there are no child controls', () => { it('should be empty when there are no child controls', () => {
var g = new ControlGroup({}); var g = new FormGroup({});
expect(g.value).toEqual({}); expect(g.value).toEqual({});
}); });
it('should support nested groups', () => { it('should support nested groups', () => {
var g = new ControlGroup( var g = new FormGroup({
{'one': new Control('111'), 'nested': new ControlGroup({'two': new Control('222')})}); 'one': new FormControl('111'),
'nested': new FormGroup({'two': new FormControl('222')})
});
expect(g.value).toEqual({'one': '111', 'nested': {'two': '222'}}); expect(g.value).toEqual({'one': '111', 'nested': {'two': '222'}});
(<Control>(g.controls['nested'].find('two'))).updateValue('333'); (<FormControl>(g.controls['nested'].find('two'))).updateValue('333');
expect(g.value).toEqual({'one': '111', 'nested': {'two': '333'}}); expect(g.value).toEqual({'one': '111', 'nested': {'two': '333'}});
}); });
@ -347,19 +349,19 @@ export function main() {
describe('adding and removing controls', () => { describe('adding and removing controls', () => {
it('should update value and validity when control is added', () => { it('should update value and validity when control is added', () => {
var g = new ControlGroup({'one': new Control('1')}); var g = new FormGroup({'one': new FormControl('1')});
expect(g.value).toEqual({'one': '1'}); expect(g.value).toEqual({'one': '1'});
expect(g.valid).toBe(true); expect(g.valid).toBe(true);
g.addControl('two', new Control('2', Validators.minLength(10))); g.addControl('two', new FormControl('2', Validators.minLength(10)));
expect(g.value).toEqual({'one': '1', 'two': '2'}); expect(g.value).toEqual({'one': '1', 'two': '2'});
expect(g.valid).toBe(false); expect(g.valid).toBe(false);
}); });
it('should update value and validity when control is removed', () => { it('should update value and validity when control is removed', () => {
var g = new ControlGroup( var g = new FormGroup(
{'one': new Control('1'), 'two': new Control('2', Validators.minLength(10))}); {'one': new FormControl('1'), 'two': new FormControl('2', Validators.minLength(10))});
expect(g.value).toEqual({'one': '1', 'two': '2'}); expect(g.value).toEqual({'one': '1', 'two': '2'});
expect(g.valid).toBe(false); expect(g.valid).toBe(false);
@ -375,8 +377,8 @@ export function main() {
var simpleValidator = (c: any /** TODO #9100 */) => var simpleValidator = (c: any /** TODO #9100 */) =>
c.controls['one'].value != 'correct' ? {'broken': true} : null; c.controls['one'].value != 'correct' ? {'broken': true} : null;
var c = new Control(null); var c = new FormControl(null);
var g = new ControlGroup({'one': c}, null, simpleValidator); var g = new FormGroup({'one': c}, null, simpleValidator);
c.updateValue('correct'); c.updateValue('correct');
@ -394,8 +396,8 @@ export function main() {
var c: any /** TODO #9100 */, g: any /** TODO #9100 */; var c: any /** TODO #9100 */, g: any /** TODO #9100 */;
beforeEach(() => { beforeEach(() => {
c = new Control('value'); c = new FormControl('value');
g = new ControlGroup({'one': c}); g = new FormGroup({'one': c});
}); });
it('should be false after creating a control', () => { expect(g.dirty).toEqual(false); }); it('should be false after creating a control', () => { expect(g.dirty).toEqual(false); });
@ -412,10 +414,10 @@ export function main() {
var group: any /** TODO #9100 */; var group: any /** TODO #9100 */;
beforeEach(() => { beforeEach(() => {
group = new ControlGroup( group = new FormGroup(
{ {
'required': new Control('requiredValue'), 'required': new FormControl('requiredValue'),
'optional': new Control('optionalValue') 'optional': new FormControl('optionalValue')
}, },
{'optional': false}); {'optional': false});
}); });
@ -437,8 +439,11 @@ export function main() {
}); });
it('should not include an inactive component into the group value', () => { it('should not include an inactive component into the group value', () => {
var group = new ControlGroup( var group = new FormGroup(
{'required': new Control('requiredValue'), 'optional': new Control('optionalValue')}, {
'required': new FormControl('requiredValue'),
'optional': new FormControl('optionalValue')
},
{'optional': false}); {'optional': false});
expect(group.value).toEqual({'required': 'requiredValue'}); expect(group.value).toEqual({'required': 'requiredValue'});
@ -449,10 +454,10 @@ export function main() {
}); });
it('should not run Validators on an inactive component', () => { it('should not run Validators on an inactive component', () => {
var group = new ControlGroup( var group = new FormGroup(
{ {
'required': new Control('requiredValue', Validators.required), 'required': new FormControl('requiredValue', Validators.required),
'optional': new Control('', Validators.required) 'optional': new FormControl('', Validators.required)
}, },
{'optional': false}); {'optional': false});
@ -468,9 +473,9 @@ export function main() {
var g: any /** TODO #9100 */, c1: any /** TODO #9100 */, c2: any /** TODO #9100 */; var g: any /** TODO #9100 */, c1: any /** TODO #9100 */, c2: any /** TODO #9100 */;
beforeEach(() => { beforeEach(() => {
c1 = new Control('old1'); c1 = new FormControl('old1');
c2 = new Control('old2'); c2 = new FormControl('old2');
g = new ControlGroup({'one': c1, 'two': c2}, {'two': true}); g = new FormGroup({'one': c1, 'two': c2}, {'two': true});
}); });
it('should fire an event after the value has been updated', it('should fire an event after the value has been updated',
@ -548,15 +553,15 @@ export function main() {
describe('getError', () => { describe('getError', () => {
it('should return the error when it is present', () => { it('should return the error when it is present', () => {
var c = new Control('', Validators.required); var c = new FormControl('', Validators.required);
var g = new ControlGroup({'one': c}); var g = new FormGroup({'one': c});
expect(c.getError('required')).toEqual(true); expect(c.getError('required')).toEqual(true);
expect(g.getError('required', ['one'])).toEqual(true); expect(g.getError('required', ['one'])).toEqual(true);
}); });
it('should return null otherwise', () => { it('should return null otherwise', () => {
var c = new Control('not empty', Validators.required); var c = new FormControl('not empty', Validators.required);
var g = new ControlGroup({'one': c}); var g = new FormGroup({'one': c});
expect(c.getError('invalid')).toEqual(null); expect(c.getError('invalid')).toEqual(null);
expect(g.getError('required', ['one'])).toEqual(null); expect(g.getError('required', ['one'])).toEqual(null);
expect(g.getError('required', ['invalid'])).toEqual(null); expect(g.getError('required', ['invalid'])).toEqual(null);
@ -565,8 +570,8 @@ export function main() {
describe('asyncValidator', () => { describe('asyncValidator', () => {
it('should run the async validator', fakeAsync(() => { it('should run the async validator', fakeAsync(() => {
var c = new Control('value'); var c = new FormControl('value');
var g = new ControlGroup({'one': c}, null, null, asyncValidator('expected')); var g = new FormGroup({'one': c}, null, null, asyncValidator('expected'));
expect(g.pending).toEqual(true); expect(g.pending).toEqual(true);
@ -577,8 +582,8 @@ export function main() {
})); }));
it('should set the parent group\'s status to pending', fakeAsync(() => { it('should set the parent group\'s status to pending', fakeAsync(() => {
var c = new Control('value', null, asyncValidator('expected')); var c = new FormControl('value', null, asyncValidator('expected'));
var g = new ControlGroup({'one': c}); var g = new FormGroup({'one': c});
expect(g.pending).toEqual(true); expect(g.pending).toEqual(true);
@ -589,8 +594,8 @@ export function main() {
it('should run the parent group\'s async validator when children are pending', it('should run the parent group\'s async validator when children are pending',
fakeAsync(() => { fakeAsync(() => {
var c = new Control('value', null, asyncValidator('expected')); var c = new FormControl('value', null, asyncValidator('expected'));
var g = new ControlGroup({'one': c}, null, null, asyncValidator('expected')); var g = new FormGroup({'one': c}, null, null, asyncValidator('expected'));
tick(1); tick(1);
@ -600,16 +605,16 @@ export function main() {
}) })
}); });
describe('ControlArray', () => { describe('FormArray', () => {
describe('adding/removing', () => { describe('adding/removing', () => {
var a: ControlArray; var a: FormArray;
var c1: any /** TODO #9100 */, c2: any /** TODO #9100 */, c3: any /** TODO #9100 */; var c1: any /** TODO #9100 */, c2: any /** TODO #9100 */, c3: any /** TODO #9100 */;
beforeEach(() => { beforeEach(() => {
a = new ControlArray([]); a = new FormArray([]);
c1 = new Control(1); c1 = new FormControl(1);
c2 = new Control(2); c2 = new FormControl(2);
c3 = new Control(3); c3 = new FormControl(3);
}); });
it('should support pushing', () => { it('should support pushing', () => {
@ -640,12 +645,12 @@ export function main() {
describe('value', () => { describe('value', () => {
it('should be the reduced value of the child controls', () => { it('should be the reduced value of the child controls', () => {
var a = new ControlArray([new Control(1), new Control(2)]); var a = new FormArray([new FormControl(1), new FormControl(2)]);
expect(a.value).toEqual([1, 2]); expect(a.value).toEqual([1, 2]);
}); });
it('should be an empty array when there are no child controls', () => { it('should be an empty array when there are no child controls', () => {
var a = new ControlArray([]); var a = new FormArray([]);
expect(a.value).toEqual([]); expect(a.value).toEqual([]);
}); });
}); });
@ -655,8 +660,8 @@ export function main() {
var simpleValidator = (c: any /** TODO #9100 */) => var simpleValidator = (c: any /** TODO #9100 */) =>
c.controls[0].value != 'correct' ? {'broken': true} : null; c.controls[0].value != 'correct' ? {'broken': true} : null;
var c = new Control(null); var c = new FormControl(null);
var g = new ControlArray([c], simpleValidator); var g = new FormArray([c], simpleValidator);
c.updateValue('correct'); c.updateValue('correct');
@ -672,12 +677,12 @@ export function main() {
describe('dirty', () => { describe('dirty', () => {
var c: Control; var c: FormControl;
var a: ControlArray; var a: FormArray;
beforeEach(() => { beforeEach(() => {
c = new Control('value'); c = new FormControl('value');
a = new ControlArray([c]); a = new FormArray([c]);
}); });
it('should be false after creating a control', () => { expect(a.dirty).toEqual(false); }); it('should be false after creating a control', () => { expect(a.dirty).toEqual(false); });
@ -690,12 +695,12 @@ export function main() {
}); });
describe('pending', () => { describe('pending', () => {
var c: Control; var c: FormControl;
var a: ControlArray; var a: FormArray;
beforeEach(() => { beforeEach(() => {
c = new Control('value'); c = new FormControl('value');
a = new ControlArray([c]); a = new FormArray([c]);
}); });
it('should be false after creating a control', () => { it('should be false after creating a control', () => {
@ -719,13 +724,13 @@ export function main() {
}); });
describe('valueChanges', () => { describe('valueChanges', () => {
var a: ControlArray; var a: FormArray;
var c1: any /** TODO #9100 */, c2: any /** TODO #9100 */; var c1: any /** TODO #9100 */, c2: any /** TODO #9100 */;
beforeEach(() => { beforeEach(() => {
c1 = new Control('old1'); c1 = new FormControl('old1');
c2 = new Control('old2'); c2 = new FormControl('old2');
a = new ControlArray([c1, c2]); a = new FormArray([c1, c2]);
}); });
it('should fire an event after the value has been updated', it('should fire an event after the value has been updated',
@ -778,23 +783,25 @@ export function main() {
describe('find', () => { describe('find', () => {
it('should return null when path is null', () => { it('should return null when path is null', () => {
var g = new ControlGroup({}); var g = new FormGroup({});
expect(g.find(null)).toEqual(null); expect(g.find(null)).toEqual(null);
}); });
it('should return null when path is empty', () => { it('should return null when path is empty', () => {
var g = new ControlGroup({}); var g = new FormGroup({});
expect(g.find([])).toEqual(null); expect(g.find([])).toEqual(null);
}); });
it('should return null when path is invalid', () => { it('should return null when path is invalid', () => {
var g = new ControlGroup({}); var g = new FormGroup({});
expect(g.find(['one', 'two'])).toEqual(null); expect(g.find(['one', 'two'])).toEqual(null);
}); });
it('should return a child of a control group', () => { it('should return a child of a control group', () => {
var g = new ControlGroup( var g = new FormGroup({
{'one': new Control('111'), 'nested': new ControlGroup({'two': new Control('222')})}); 'one': new FormControl('111'),
'nested': new FormGroup({'two': new FormControl('222')})
});
expect(g.find(['nested', 'two']).value).toEqual('222'); expect(g.find(['nested', 'two']).value).toEqual('222');
expect(g.find(['one']).value).toEqual('111'); expect(g.find(['one']).value).toEqual('111');
@ -803,7 +810,7 @@ export function main() {
}); });
it('should return an element of an array', () => { it('should return an element of an array', () => {
var g = new ControlGroup({'array': new ControlArray([new Control('111')])}); var g = new FormGroup({'array': new FormArray([new FormControl('111')])});
expect(g.find(['array', 0]).value).toEqual('111'); expect(g.find(['array', 0]).value).toEqual('111');
}); });
@ -811,8 +818,8 @@ export function main() {
describe('asyncValidator', () => { describe('asyncValidator', () => {
it('should run the async validator', fakeAsync(() => { it('should run the async validator', fakeAsync(() => {
var c = new Control('value'); var c = new FormControl('value');
var g = new ControlArray([c], null, asyncValidator('expected')); var g = new FormArray([c], null, asyncValidator('expected'));
expect(g.pending).toEqual(true); expect(g.pending).toEqual(true);

View File

@ -1,4 +1,4 @@
import {AbstractControl, Control, ControlArray, ControlGroup, Validators} from '@angular/common'; import {AbstractControl, FormControl, Validators} from '@angular/common/src/forms';
import {Log, fakeAsync, flushMicrotasks, tick} from '@angular/core/testing'; import {Log, fakeAsync, flushMicrotasks, tick} from '@angular/core/testing';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal'; import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
@ -17,30 +17,30 @@ export function main() {
describe('Validators', () => { describe('Validators', () => {
describe('required', () => { describe('required', () => {
it('should error on an empty string', it('should error on an empty string',
() => { expect(Validators.required(new Control(''))).toEqual({'required': true}); }); () => { expect(Validators.required(new FormControl(''))).toEqual({'required': true}); });
it('should error on null', it('should error on null',
() => { expect(Validators.required(new Control(null))).toEqual({'required': true}); }); () => { expect(Validators.required(new FormControl(null))).toEqual({'required': true}); });
it('should not error on a non-empty string', it('should not error on a non-empty string',
() => { expect(Validators.required(new Control('not empty'))).toEqual(null); }); () => { expect(Validators.required(new FormControl('not empty'))).toEqual(null); });
it('should accept zero as valid', it('should accept zero as valid',
() => { expect(Validators.required(new Control(0))).toEqual(null); }); () => { expect(Validators.required(new FormControl(0))).toEqual(null); });
}); });
describe('minLength', () => { describe('minLength', () => {
it('should not error on an empty string', it('should not error on an empty string',
() => { expect(Validators.minLength(2)(new Control(''))).toEqual(null); }); () => { expect(Validators.minLength(2)(new FormControl(''))).toEqual(null); });
it('should not error on null', it('should not error on null',
() => { expect(Validators.minLength(2)(new Control(null))).toEqual(null); }); () => { expect(Validators.minLength(2)(new FormControl(null))).toEqual(null); });
it('should not error on valid strings', it('should not error on valid strings',
() => { expect(Validators.minLength(2)(new Control('aa'))).toEqual(null); }); () => { expect(Validators.minLength(2)(new FormControl('aa'))).toEqual(null); });
it('should error on short strings', () => { it('should error on short strings', () => {
expect(Validators.minLength(2)(new Control('a'))).toEqual({ expect(Validators.minLength(2)(new FormControl('a'))).toEqual({
'minlength': {'requiredLength': 2, 'actualLength': 1} 'minlength': {'requiredLength': 2, 'actualLength': 1}
}); });
}); });
@ -48,16 +48,16 @@ export function main() {
describe('maxLength', () => { describe('maxLength', () => {
it('should not error on an empty string', it('should not error on an empty string',
() => { expect(Validators.maxLength(2)(new Control(''))).toEqual(null); }); () => { expect(Validators.maxLength(2)(new FormControl(''))).toEqual(null); });
it('should not error on null', it('should not error on null',
() => { expect(Validators.maxLength(2)(new Control(null))).toEqual(null); }); () => { expect(Validators.maxLength(2)(new FormControl(null))).toEqual(null); });
it('should not error on valid strings', it('should not error on valid strings',
() => { expect(Validators.maxLength(2)(new Control('aa'))).toEqual(null); }); () => { expect(Validators.maxLength(2)(new FormControl('aa'))).toEqual(null); });
it('should error on long strings', () => { it('should error on long strings', () => {
expect(Validators.maxLength(2)(new Control('aaa'))).toEqual({ expect(Validators.maxLength(2)(new FormControl('aaa'))).toEqual({
'maxlength': {'requiredLength': 2, 'actualLength': 3} 'maxlength': {'requiredLength': 2, 'actualLength': 3}
}); });
}); });
@ -65,16 +65,17 @@ export function main() {
describe('pattern', () => { describe('pattern', () => {
it('should not error on an empty string', it('should not error on an empty string',
() => { expect(Validators.pattern('[a-zA-Z ]*')(new Control(''))).toEqual(null); }); () => { expect(Validators.pattern('[a-zA-Z ]*')(new FormControl(''))).toEqual(null); });
it('should not error on null', it('should not error on null',
() => { expect(Validators.pattern('[a-zA-Z ]*')(new Control(null))).toEqual(null); }); () => { expect(Validators.pattern('[a-zA-Z ]*')(new FormControl(null))).toEqual(null); });
it('should not error on valid strings', it('should not error on valid strings', () => {
() => { expect(Validators.pattern('[a-zA-Z ]*')(new Control('aaAA'))).toEqual(null); }); expect(Validators.pattern('[a-zA-Z ]*')(new FormControl('aaAA'))).toEqual(null);
});
it('should error on failure to match string', () => { it('should error on failure to match string', () => {
expect(Validators.pattern('[a-zA-Z ]*')(new Control('aaa0'))).toEqual({ expect(Validators.pattern('[a-zA-Z ]*')(new FormControl('aaa0'))).toEqual({
'pattern': {'requiredPattern': '^[a-zA-Z ]*$', 'actualValue': 'aaa0'} 'pattern': {'requiredPattern': '^[a-zA-Z ]*$', 'actualValue': 'aaa0'}
}); });
}); });
@ -86,22 +87,22 @@ export function main() {
it('should collect errors from all the validators', () => { it('should collect errors from all the validators', () => {
var c = Validators.compose([validator('a', true), validator('b', true)]); var c = Validators.compose([validator('a', true), validator('b', true)]);
expect(c(new Control(''))).toEqual({'a': true, 'b': true}); expect(c(new FormControl(''))).toEqual({'a': true, 'b': true});
}); });
it('should run validators left to right', () => { it('should run validators left to right', () => {
var c = Validators.compose([validator('a', 1), validator('a', 2)]); var c = Validators.compose([validator('a', 1), validator('a', 2)]);
expect(c(new Control(''))).toEqual({'a': 2}); expect(c(new FormControl(''))).toEqual({'a': 2});
}); });
it('should return null when no errors', () => { it('should return null when no errors', () => {
var c = Validators.compose([Validators.nullValidator, Validators.nullValidator]); var c = Validators.compose([Validators.nullValidator, Validators.nullValidator]);
expect(c(new Control(''))).toEqual(null); expect(c(new FormControl(''))).toEqual(null);
}); });
it('should ignore nulls', () => { it('should ignore nulls', () => {
var c = Validators.compose([null, Validators.required]); var c = Validators.compose([null, Validators.required]);
expect(c(new Control(''))).toEqual({'required': true}); expect(c(new FormControl(''))).toEqual({'required': true});
}); });
}); });
@ -131,7 +132,7 @@ export function main() {
]); ]);
var value: any /** TODO #9100 */ = null; var value: any /** TODO #9100 */ = null;
(<Promise<any>>c(new Control('invalid'))).then(v => value = v); (<Promise<any>>c(new FormControl('invalid'))).then(v => value = v);
tick(1); tick(1);
@ -142,7 +143,7 @@ export function main() {
var c = Validators.composeAsync([asyncValidator('expected', {'one': true})]); var c = Validators.composeAsync([asyncValidator('expected', {'one': true})]);
var value: any /** TODO #9100 */ = null; var value: any /** TODO #9100 */ = null;
(<Promise<any>>c(new Control('expected'))).then(v => value = v); (<Promise<any>>c(new FormControl('expected'))).then(v => value = v);
tick(1); tick(1);
@ -153,7 +154,7 @@ export function main() {
var c = Validators.composeAsync([asyncValidator('expected', {'one': true}), null]); var c = Validators.composeAsync([asyncValidator('expected', {'one': true}), null]);
var value: any /** TODO #9100 */ = null; var value: any /** TODO #9100 */ = null;
(<Promise<any>>c(new Control('invalid'))).then(v => value = v); (<Promise<any>>c(new FormControl('invalid'))).then(v => value = v);
tick(1); tick(1);