import { Component } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; @Component({ selector: 'app-root', template: ` <h2>Reactive Form</h2> <form novalidate [formGroup]="user" (ngSubmit)="submitForm(user.value)"> <div style="margin-bottom:20px"> <label [for]="name" align="top">Name:</label> <eui-textbox #name formControlName="name" [invalid]="user.get('name').invalid"></eui-textbox> <div class="error" *ngIf="user.get('name').hasError('required')">This field is required.</div> </div> <div style="margin-bottom:20px"> <label [for]="email" align="top">Email:</label> <eui-textbox #email formControlName="email" [invalid]="user.get('email').invalid"></eui-textbox> <div class="error" *ngIf="user.get('email').hasError('pattern')">Please enter a valid email address.</div> </div> <div style="margin-bottom:20px"> <label [for]="hero" align="top">Select a hero:</label> <eui-combobox #hero formControlName="hero" [data]="heroes"></eui-combobox> </div> <div style="margin-bottom:20px"> <eui-checkbox #accept formControlName="accept"></eui-checkbox> <label [for]="accept">Accept Me</label> </div> <div style="margin-bottom:20px"> <eui-linkbutton [disabled]="user.invalid" (click)="submitForm(user.value)">Submit</eui-linkbutton> </div> </form> `, styles: [` .error{ color: red; font-size: 12px; margin: 4px 0; } `] }) export class AppComponent { user: FormGroup; constructor(fb: FormBuilder){ this.user = fb.group({ 'name': [null, Validators.required], 'email': ['test@jeasyui.com', Validators.pattern('^[a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$')], 'hero': null, 'accept': false }); } submitForm(value: any) { alert(JSON.stringify(value)) } heroes = [ {value: 11, text: 'Mr. Nice'}, {value: 12, text: 'Narco'}, {value: 13, text: 'Bombasto'}, {value: 14, text: 'Celeritas'}, {value: 15, text: 'Magneta'}, {value: 16, text: 'RubberMan'}, {value: 17, text: 'Dynama'}, {value: 18, text: 'Dr IQ'}, {value: 19, text: 'Magma'}, {value: 20, text: 'Tornado'} ]; }
import { NgModule } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { BrowserModule } from '@angular/platform-browser'; import { HttpModule } from '@angular/http'; import { EasyUIModule } from 'easyui/easyui/easyui.module'; import { AppComponent } from './app.component'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, ReactiveFormsModule, BrowserModule, HttpModule, EasyUIModule ] }) export class AppModule { }
import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app.module'; enableProdMode(); platformBrowserDynamic().bootstrapModule(AppModule);