angular-cn/modules/angular2/src/forms/form_builder.js

62 lines
2.0 KiB
JavaScript
Raw Normal View History

import {StringMapWrapper, ListWrapper, List} from 'angular2/src/facade/collection';
2015-03-10 18:12:50 -07:00
import {isPresent} from 'angular2/src/facade/lang';
import * as modelModule from './model';
2015-03-10 18:12:50 -07:00
/**
* @exportedAs angular2/forms
*/
2015-03-10 18:12:50 -07:00
export class FormBuilder {
group(controlsConfig, extra = null):modelModule.ControlGroup {
2015-03-10 18:12:50 -07:00
var controls = this._reduceControls(controlsConfig);
var optionals = isPresent(extra) ? StringMapWrapper.get(extra, "optionals") : null;
var validator = isPresent(extra) ? StringMapWrapper.get(extra, "validator") : null;
if (isPresent(validator)) {
return new modelModule.ControlGroup(controls, optionals, validator);
2015-03-10 18:12:50 -07:00
} else {
return new modelModule.ControlGroup(controls, optionals);
2015-03-10 18:12:50 -07:00
}
}
control(value, validator:Function = null):modelModule.Control {
2015-03-10 18:12:50 -07:00
if (isPresent(validator)) {
return new modelModule.Control(value, validator);
2015-03-10 18:12:50 -07:00
} else {
return new modelModule.Control(value);
2015-03-10 18:12:50 -07:00
}
}
array(controlsConfig:List, validator:Function = null):modelModule.ControlArray {
var controls = ListWrapper.map(controlsConfig, (c) => this._createControl(c));
if (isPresent(validator)) {
return new modelModule.ControlArray(controls, validator);
} else {
return new modelModule.ControlArray(controls);
}
}
2015-03-10 18:12:50 -07:00
_reduceControls(controlsConfig) {
var controls = {};
StringMapWrapper.forEach(controlsConfig, (controlConfig, controlName) => {
controls[controlName] = this._createControl(controlConfig);
});
return controls;
}
_createControl(controlConfig) {
if (controlConfig instanceof modelModule.Control ||
controlConfig instanceof modelModule.ControlGroup ||
controlConfig instanceof modelModule.ControlArray) {
2015-03-10 18:12:50 -07:00
return controlConfig;
} else if (ListWrapper.isList(controlConfig)) {
var value = ListWrapper.get(controlConfig, 0);
var validator = controlConfig.length > 1 ? controlConfig[1] : null;
return this.control(value, validator);
} else {
return this.control(controlConfig);
}
}
}