/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Component, Host, NgModule} from '@angular/core';
import {isPresent, print} from '@angular/core/src/facade/lang';
import {AbstractControl, FormBuilder, FormGroup, FormGroupDirective, ReactiveFormsModule, Validators} from '@angular/forms';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
/**
* Custom validator.
*/
function creditCardValidator(c: AbstractControl): {[key: string]: boolean} {
if (isPresent(c.value) && /^\d{16}$/.test(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'],
template: `
{{errorMessage}}
`
})
class ShowError {
formDir: any /** TODO #9100 */;
controlPath: string;
errorTypes: string[];
constructor(@Host() formDir: FormGroupDirective) { this.formDir = formDir; }
get errorMessage(): string {
var form: FormGroup = this.formDir.form;
var control = form.get(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;
}
private _errorMessage(code: string): string {
var config = {'required': 'is required', 'invalidCreditCard': 'is invalid credit card number'};
return (config as any /** TODO #9100 */)[code];
}
}
@Component({
selector: 'reactive-forms',
viewProviders: [FormBuilder],
template: `
Checkout Form (Reactive)
`
})
class ReactiveForms {
form: any /** TODO #9100 */;
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);
}
}
@NgModule({
bootstrap: [ReactiveForms],
declarations: [ShowError, ReactiveForms],
imports: [BrowserModule, ReactiveFormsModule]
})
class ExampleModule {
}
export function main() {
platformBrowserDynamic().bootstrapModule(ExampleModule);
}