Angular 中的表单功能强大且易于使用。
让我们用 Reactive Form 构建一个简单的表单。
1:我们抓取所有我们需要使用 Reactive Form 的 NgModule 并使用 Http 调用 AJAX:
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
imports: [
BrowserModule,
HttpModule, // for http request
ReactiveFormsModule // for form system
],
declarations: [ AppComponent ],
providers: [ ],
bootstrap: [ AppComponent ]
})
export class AppModule {}
2:我们的 AppComponent 看起来像这样:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { FromGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-form',
template: `
<h2>Contact Form</h2>
<form [formGroup]="frmContact" (ngSubmit)="onSubmit()" novalidate>
<div>
<label>
Name:
<input type="text" formControlName="name">
</label>
</div>
<div>
<label>
Comment:
<textarea formControlName="content"></textarea>
</label>
</div>
<button [disabled]="frmContact.invalid">Submit</button>
</form>
<div *ngIf="res">
Response:
<pre>{{ res | json }}</pre>
</div>
`,
})
export class AppComponent implements OnInit, OnDestroy {
frmContact: FormGroup;
private _sub;
res: any;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.frmContact = this.fb.group({
name: ['', Validators.required],
content: ['', Validators.required]
});
}
onSubmit() {
let formValue = this.frmContact.value;
// cool stuff to transform form value
// call AJAX
}
ngOnDestroy() {
// clean subscription when component destroy
if (this._sub) {
this._sub.unsubscribe();
}
}
}
我们在组件初始化时将 FormBuilder 类注入 AppComponent 以创建我们的表单。
我们使用Validators 来使用预构建的验证器功能 - 例如required。
在组件模板中,我们使用一些指令formGroup,formControlName 将我们的表单绑定到模板。
3:现在,我们需要一个服务来与服务器通信:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class PostService {
private API_ENDPOINT = '//jsonplaceholder.typicode.com/posts'; //replace with your API ENDPOINT
constructor(private _http: Http) {}
saveContact(contact: any) {
return this._http.post(this.API_ENDPOINT, contact)
.map(res => res.json());
}
}
也许在某些情况下,您需要包含标头(例如授权令牌),您需要像这样创建标头:
let headers = new Headers({ 'Content-Type': 'application/json' }); // create new Headers object with header Content-Type is application/json.
headers.append('Authorization', 'Bearer ' + your_token); //JWT token
let options = new RequestOptions({ headers: headers });
并发送带有标头的请求:
saveContact(contact: any) {
let headers = new Headers({ 'Content-Type': 'application/json' }); // create new Headers object with header Content-Type is application/json.
headers.append('Authorization', 'Bearer ' + your_token); //JWT token
let options = new RequestOptions({ headers: headers });
return this._http.post(this.API_ENDPOINT, contact, options)
.map(res => res.json());
}
4:更新 AppComponent 和 AppModule 以使用服务
AppModule
// other import
import { PostService } from './post.service';
@NgModule({
imports: [
//...
],
declarations: [ AppComponent ],
providers: [ PostService ], // declare our service into this array
bootstrap: [ AppComponent ]
})
export class AppModule {}
应用组件
// other import
import { PostService } from './post.service';
@Component({
//...
})
export class AppComponent implements OnInit, OnDestroy {
frmContact: FormGroup;
private _sub;
res: any;
constructor(private fb: FormBuilder, private postService: PostService) {}
ngOnInit() {
//...
}
onSubmit() {
let formValue = this.frmContact.value;
// cool stuff to transform form value
// call AJAX
this._sub = this.postService.saveContact(formValue)
.subscribe(data => {
console.log(data)
this.res = data;
});
}
ngOnDestroy() {
// clean subscription when component destroy
if (this._sub) {
this._sub.unsubscribe();
}
}
}
当用户点击按钮提交时,onSubmit方法会执行,然后它会调用服务方法this.postService.saveContact发送你的数据。
你可以在这里玩现场演示:https://plnkr.co/edit/GCYsGwreHi13FejcWDtE?p=preview
文档:https://angular.io/docs/ts/latest/guide/server-communication.html