import {bootstrap} from 'angular2/bootstrap'; import { FORM_DIRECTIVES, ControlGroup, NgControl, Validators, NgFormModel, FormBuilder, NgIf, NgFor, Component, Directive, View, Host } from 'angular2/core'; import {RegExpWrapper, print, isPresent} from 'angular2/src/facade/lang'; /** * Custom validator. */ function creditCardValidator(c): {[key: string]: boolean} { if (isPresent(c.value) && RegExpWrapper.test(/^\d{16}$/g, c.value)) { return null; } else { return {"invalidCreditCard": true}; } } /** * This is a component that displays an error message. * * For instance, * * * * Will display the "is required" error if the control is empty, and "invalid credit card" if the * control is not empty * but not valid. * * In a real application, this component would receive a service that would map an error code to an * actual error message. * To make it simple, we are using a simple map here. */ @Component({selector: 'show-error', inputs: ['controlPath: control', 'errorTypes: errors']}) @View({ template: ` {{errorMessage}} `, directives: [NgIf] }) class ShowError { formDir; controlPath: string; errorTypes: string[]; constructor(@Host() formDir: NgFormModel) { this.formDir = formDir; } get errorMessage(): string { var form: ControlGroup = this.formDir.form; var control = form.find(this.controlPath); if (isPresent(control) && control.touched) { for (var i = 0; i < this.errorTypes.length; ++i) { if (control.hasError(this.errorTypes[i])) { return this._errorMessage(this.errorTypes[i]); } } } return null; } _errorMessage(code: string): string { var config = {'required': 'is required', 'invalidCreditCard': 'is invalid credit card number'}; return config[code]; } } @Component({selector: 'model-driven-forms', viewProviders: [FormBuilder]}) @View({ template: `

Checkout Form (Model Driven)

`, directives: [FORM_DIRECTIVES, NgFor, ShowError] }) class ModelDrivenForms { form; countries = ['US', 'Canada']; constructor(fb: FormBuilder) { this.form = fb.group({ "firstName": ["", Validators.required], "middleName": [""], "lastName": ["", Validators.required], "country": ["Canada", Validators.required], "creditCard": ["", Validators.compose([Validators.required, creditCardValidator])], "amount": [0, Validators.required], "email": ["", Validators.required], "comments": [""] }); } onSubmit(): void { print("Submitting:"); print(this.form.value); } } export function main() { bootstrap(ModelDrivenForms); }