forked from angular/angular
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathform_builder.js
More file actions
80 lines (71 loc) · 2.54 KB
/
form_builder.js
File metadata and controls
80 lines (71 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import {StringMapWrapper, ListWrapper, List} from 'angular2/src/facade/collection';
import {isPresent} from 'angular2/src/facade/lang';
import * as modelModule from './model';
/**
* Creates a form object from a user-specified configuration.
*
* # Example
*
* This example creates a {@link ControlGroup} that consists of a `login` {@link Control}, and a nested
* {@link ControlGroup} that defines a `password` and a `passwordConfirmation` {@link Control}.
*
* ```
* var loginForm = builder.group({
* login: ["", Validators.required],
*
* passwordRetry: builder.group({
* password: ["", Validators.required],
* passwordConfirmation: ["", Validators.required]
* })
* });
*
* ```
* @exportedAs angular2/forms
*/
export class FormBuilder {
group(controlsConfig, extra = null):modelModule.ControlGroup {
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);
} else {
return new modelModule.ControlGroup(controls, optionals);
}
}
control(value, validator:Function = null):modelModule.Control {
if (isPresent(validator)) {
return new modelModule.Control(value, validator);
} else {
return new modelModule.Control(value);
}
}
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);
}
}
_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) {
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);
}
}
}