feat(forms): implemented template-driven forms

This commit is contained in:
vsavkin
2015-05-30 11:56:00 -07:00
parent 5c53cf6486
commit a9d6fd9afa
19 changed files with 835 additions and 349 deletions

View File

@ -0,0 +1,37 @@
import {ElementRef, Directive} from 'angular2/angular2';
import {Renderer} from 'angular2/src/render/api';
import {ControlDirective} from './control_directive';
import {ControlValueAccessor} from './control_value_accessor';
/**
* The accessor for writing a value and listening to changes on a checkbox input element.
*
*
* # Example
* ```
* <input type="checkbox" [control]="rememberLogin">
* ```
*
* @exportedAs angular2/forms
*/
@Directive({
selector: 'input[type=checkbox][control],input[type=checkbox][form-control]',
hostListeners: {'change': 'onChange($event.target.checked)'},
hostProperties: {'checked': 'checked'}
})
export class CheckboxControlValueAccessor implements ControlValueAccessor {
checked: boolean;
onChange: Function;
constructor(cd: ControlDirective, private _elementRef: ElementRef, private _renderer: Renderer) {
this.onChange = (_) => {};
cd.valueAccessor = this;
}
writeValue(value) {
this._renderer.setElementProperty(this._elementRef.parentView.render,
this._elementRef.boundElementIndex, 'checked', value)
}
registerOnChange(fn) { this.onChange = fn; }
}

View File

@ -0,0 +1,8 @@
import {FormDirective} from './form_directive';
import {List} from 'angular2/src/facade/collection';
export class ControlContainerDirective {
name: string;
get formDirective(): FormDirective { return null; }
get path(): List<string> { return null; }
}

View File

@ -0,0 +1,11 @@
import {ControlValueAccessor} from './control_value_accessor';
import {Validators} from '../validators';
export class ControlDirective {
name: string = null;
valueAccessor: ControlValueAccessor = null;
validator: Function;
get path(): List<string> { return null; }
constructor() { this.validator = Validators.nullValidator; }
}

View File

@ -0,0 +1,73 @@
import {Directive, Ancestor, onDestroy, onInit} from 'angular2/angular2';
import {Inject, FORWARD_REF, Binding} from 'angular2/di';
import {List, ListWrapper} from 'angular2/src/facade/collection';
import {CONST_EXPR} from 'angular2/src/facade/lang';
import {ControlContainerDirective} from './control_container_directive';
import {controlPath} from './shared';
const controlGroupBinding = CONST_EXPR(
new Binding(ControlContainerDirective, {toAlias: FORWARD_REF(() => ControlGroupDirective)}));
/**
* Binds a control group to a DOM element.
*
* # Example
*
* In this example, we bind the control group to the form element, and we bind the login and
* password controls to the
* login and password elements.
*
* Here we use {@link formDirectives}, rather than importing each form directive individually, e.g.
* `ControlDirective`, `ControlGroupDirective`. This is just a shorthand for the same end result.
*
* ```
* @Component({selector: "login-comp"})
* @View({
* directives: [formDirectives],
* template: "<form [control-group]='loginForm'>" +
* "Login <input type='text' control='login'>" +
* "Password <input type='password' control='password'>" +
* "<button (click)="onLogin()">Login</button>" +
* "</form>"
* })
* class LoginComp {
* loginForm:ControlGroup;
*
* constructor() {
* this.loginForm = new ControlGroup({
* login: new Control(""),
* password: new Control("")
* });
* }
*
* onLogin() {
* // this.loginForm.value
* }
* }
*
* ```
*
* @exportedAs angular2/forms
*/
@Directive({
selector: '[control-group]',
hostInjector: [controlGroupBinding],
properties: ['name: control-group'],
lifecycle: [onInit, onDestroy]
})
export class ControlGroupDirective extends ControlContainerDirective {
_parent: ControlContainerDirective;
constructor(@Ancestor() _parent: ControlContainerDirective) {
super();
this._parent = _parent;
}
onInit() { this.formDirective.addControlGroup(this); }
onDestroy() { this.formDirective.removeControlGroup(this); }
get path(): List<string> { return controlPath(this.name, this._parent); }
get formDirective(): any { return this._parent.formDirective; }
}

View File

@ -0,0 +1,65 @@
import {CONST_EXPR} from 'angular2/src/facade/lang';
import {List} from 'angular2/src/facade/collection';
import {Directive, Ancestor, onDestroy, onInit} from 'angular2/angular2';
import {FORWARD_REF, Binding, Inject} from 'angular2/di';
import {ControlContainerDirective} from './control_container_directive';
import {ControlDirective} from './control_directive';
import {controlPath} from './shared';
const controlNameBinding =
CONST_EXPR(new Binding(ControlDirective, {toAlias: FORWARD_REF(() => ControlNameDirective)}));
/**
* Binds a control to a DOM element.
*
* # Example
*
* In this example, we bind the control to an input element. When the value of the input element
* changes, the value of
* the control will reflect that change. Likewise, if the value of the control changes, the input
* element reflects that
* change.
*
* Here we use {@link formDirectives}, rather than importing each form directive individually, e.g.
* `ControlDirective`, `ControlGroupDirective`. This is just a shorthand for the same end result.
*
* ```
* @Component({selector: "login-comp"})
* @View({
* directives: [formDirectives],
* template: "<input type='text' [control]='loginControl'>"
* })
* class LoginComp {
* loginControl:Control;
*
* constructor() {
* this.loginControl = new Control('');
* }
* }
*
* ```
*
* @exportedAs angular2/forms
*/
@Directive({
selector: '[control]',
hostInjector: [controlNameBinding],
properties: ['name: control'],
lifecycle: [onDestroy, onInit]
})
export class ControlNameDirective extends ControlDirective {
_parent: ControlContainerDirective;
constructor(@Ancestor() _parent: ControlContainerDirective) {
super();
this._parent = _parent;
}
onInit() { this.formDirective.addControl(this); }
onDestroy() { this.formDirective.removeControl(this); }
get path(): List<string> { return controlPath(this.name, this._parent); }
get formDirective(): any { return this._parent.formDirective; }
}

View File

@ -0,0 +1,4 @@
export interface ControlValueAccessor {
writeValue(obj: any): void;
registerOnChange(fun: any): void;
}

View File

@ -0,0 +1,41 @@
import {ElementRef, Directive} from 'angular2/angular2';
import {Renderer} from 'angular2/src/render/api';
import {ControlDirective} from './control_directive';
import {ControlValueAccessor} from './control_value_accessor';
/**
* The default accessor for writing a value and listening to changes that is used by a {@link
* Control} directive.
*
* This is the default strategy that Angular uses when no other accessor is applied.
*
* # Example
* ```
* <input type="text" [control]="loginControl">
* ```
*
* @exportedAs angular2/forms
*/
@Directive({
selector:
'input:not([type=checkbox])[control],textarea[control],input:not([type=checkbox])[form-control],textarea[form-control]',
hostListeners:
{'change': 'onChange($event.target.value)', 'input': 'onChange($event.target.value)'},
hostProperties: {'value': 'value'}
})
export class DefaultValueAccessor implements ControlValueAccessor {
value = null;
onChange: Function;
constructor(cd: ControlDirective, private _elementRef: ElementRef, private _renderer: Renderer) {
this.onChange = (_) => {};
cd.valueAccessor = this;
}
writeValue(value) {
this._renderer.setElementProperty(this._elementRef.parentView.render,
this._elementRef.boundElementIndex, 'value', value)
}
registerOnChange(fn) { this.onChange = fn; }
}

View File

@ -0,0 +1,25 @@
import {CONST_EXPR} from 'angular2/src/facade/lang';
import {Directive, Ancestor, onChange} from 'angular2/angular2';
import {FORWARD_REF, Binding} from 'angular2/di';
import {ControlDirective} from './control_directive';
import {Control} from '../model';
import {setUpControl} from './shared';
const formControlBinding =
CONST_EXPR(new Binding(ControlDirective, {toAlias: FORWARD_REF(() => FormControlDirective)}));
@Directive({
selector: '[form-control]',
hostInjector: [formControlBinding],
properties: ['control: form-control'],
lifecycle: [onChange]
})
export class FormControlDirective extends ControlDirective {
control: Control;
onChange(_) {
setUpControl(this.control, this);
this.control.updateValidity();
}
}

View File

@ -0,0 +1,9 @@
import {ControlDirective} from './control_directive';
import {ControlGroupDirective} from './control_group_directive';
export interface FormDirective {
addControl(dir: ControlDirective): void;
removeControl(dir: ControlDirective): void;
addControlGroup(dir: ControlGroupDirective): void;
removeControlGroup(dir: ControlGroupDirective): void;
}

View File

@ -0,0 +1,55 @@
import {CONST_EXPR} from 'angular2/src/facade/lang';
import {List, ListWrapper} from 'angular2/src/facade/collection';
import {Directive, onChange} from 'angular2/angular2';
import {FORWARD_REF, Binding} from 'angular2/di';
import {ControlDirective} from './control_directive';
import {ControlGroupDirective} from './control_group_directive';
import {ControlContainerDirective} from './control_container_directive';
import {FormDirective} from './form_directive';
import {ControlGroup} from '../model';
import {setUpControl} from './shared';
const formDirectiveBinding = CONST_EXPR(
new Binding(ControlContainerDirective, {toAlias: FORWARD_REF(() => FormModelDirective)}));
@Directive({
selector: '[form-model]',
hostInjector: [formDirectiveBinding],
properties: ['form: form-model'],
lifecycle: [onChange]
})
export class FormModelDirective extends ControlContainerDirective implements FormDirective {
form: ControlGroup = null;
directives: List<ControlDirective>;
constructor() {
super();
this.directives = [];
}
onChange(_) { this._updateDomValue(); }
get formDirective(): FormDirective { return this; }
get path(): List<string> { return []; }
addControl(dir: ControlDirective): void {
var c: any = this.form.find(dir.path);
setUpControl(c, dir);
c.updateValidity();
ListWrapper.push(this.directives, dir);
}
removeControl(dir: ControlDirective): void { ListWrapper.remove(this.directives, dir); }
addControlGroup(dir: ControlGroupDirective) {}
removeControlGroup(dir: ControlGroupDirective) {}
_updateDomValue() {
ListWrapper.forEach(this.directives, dir => {
var c: any = this.form.find(dir.path);
dir.valueAccessor.writeValue(c.value);
});
}
}

View File

@ -0,0 +1,41 @@
import {ElementRef, Directive} from 'angular2/angular2';
import {Renderer} from 'angular2/src/render/api';
import {ControlDirective} from './control_directive';
import {ControlValueAccessor} from './control_value_accessor';
/**
* The accessor for writing a value and listening to changes that is used by a {@link
* Control} directive.
*
* This is the default strategy that Angular uses when no other accessor is applied.
*
* # Example
* ```
* <input type="text" [control]="loginControl">
* ```
*
* @exportedAs angular2/forms
*/
@Directive({
selector: 'select[control],select[form-control]',
hostListeners:
{'change': 'onChange($event.target.value)', 'input': 'onChange($event.target.value)'},
hostProperties: {'value': 'value'}
})
export class SelectControlValueAccessor implements ControlValueAccessor {
value = null;
onChange: Function;
constructor(cd: ControlDirective, private _elementRef: ElementRef, private _renderer: Renderer) {
this.onChange = (_) => {};
this.value = '';
cd.valueAccessor = this;
}
writeValue(value) {
this._renderer.setElementProperty(this._elementRef.parentView.render,
this._elementRef.boundElementIndex, 'value', value)
}
registerOnChange(fn) { this.onChange = fn; }
}

View File

@ -0,0 +1,27 @@
import {ListWrapper} from 'angular2/src/facade/collection';
import {isBlank, BaseException} from 'angular2/src/facade/lang';
import {ControlContainerDirective} from './control_container_directive';
import {ControlDirective} from './control_directive';
import {Control} from '../model';
import {Validators} from '../validators';
export function controlPath(name, parent: ControlContainerDirective) {
var p = ListWrapper.clone(parent.path);
ListWrapper.push(p, name);
return p;
}
export function setUpControl(c: Control, dir: ControlDirective) {
if (isBlank(c)) _throwError(dir, "Cannot find control");
if (isBlank(dir.valueAccessor)) _throwError(dir, "No value accessor for");
c.validator = Validators.compose([c.validator, dir.validator]);
dir.valueAccessor.writeValue(c.value);
dir.valueAccessor.registerOnChange(newValue => c.updateValue(newValue));
}
function _throwError(dir: ControlDirective, message: string): void {
var path = ListWrapper.join(dir.path, " -> ");
throw new BaseException(`${message} '${path}'`);
}

View File

@ -0,0 +1,75 @@
import {PromiseWrapper} from 'angular2/src/facade/async';
import {StringMapWrapper, List, ListWrapper} from 'angular2/src/facade/collection';
import {isPresent, CONST_EXPR} from 'angular2/src/facade/lang';
import {Directive} from 'angular2/src/core/annotations/decorators';
import {FORWARD_REF, Binding} from 'angular2/di';
import {ControlDirective} from './control_directive';
import {FormDirective} from './form_directive';
import {ControlGroupDirective} from './control_group_directive';
import {ControlContainerDirective} from './control_container_directive';
import {AbstractControl, ControlGroup, Control} from '../model';
import {setUpControl} from './shared';
const formDirectiveBinding = CONST_EXPR(new Binding(
ControlContainerDirective, {toAlias: FORWARD_REF(() => TemplateDrivenFormDirective)}));
@Directive({selector: '[form]', hostInjector: [formDirectiveBinding]})
export class TemplateDrivenFormDirective extends ControlContainerDirective implements
FormDirective {
form: ControlGroup;
constructor() {
super();
this.form = new ControlGroup({});
}
get formDirective(): FormDirective { return this; }
get path(): List<string> { return []; }
get controls(): StringMap<string, AbstractControl> { return this.form.controls; }
get value(): any { return this.form.value; }
addControl(dir: ControlDirective): void {
this._later(_ => {
var group = this._findContainer(dir.path);
var c = new Control("");
setUpControl(c, dir);
group.addControl(dir.name, c);
});
}
removeControl(dir: ControlDirective): void {
this._later(_ => {
var c = this._findContainer(dir.path);
if (isPresent(c)) c.removeControl(dir.name)
});
}
addControlGroup(dir: ControlGroupDirective): void {
this._later(_ => {
var group = this._findContainer(dir.path);
var c = new ControlGroup({});
group.addControl(dir.name, c);
});
}
removeControlGroup(dir: ControlGroupDirective): void {
this._later(_ => {
var c = this._findContainer(dir.path);
if (isPresent(c)) c.removeControl(dir.name)
});
}
_findContainer(path: List<string>): ControlGroup {
ListWrapper.removeLast(path);
return <ControlGroup>this.form.find(path);
}
_later(fn) {
var c = PromiseWrapper.completer();
PromiseWrapper.then(c.promise, fn, (_) => {});
c.resolve(null);
}
}