1、新建项目
ng new forms
cd forms
cnpm install
ng serve --open
2、要使用angular的表单,需要在NgModule中引入FormsModule或者ReactiveFormsModule
FormsModule用于 ngModel和NgForm
ReactiveFormsModule用于 formControl和ngFormGroup
当使用了FormsModule,NgForm会自动附加到视图上的form表单上,NgForm会默认包含以下两点:
1)一个名为ngForm的 FormGroup
- A (ngSubmit) Output
import {FormsModule,ReactiveFormsModule} from '@angular/forms';
@NgModule({
declarations: [
FormsDemoApp,
DemoFormSkuComponent,
// ... our declarations here
],
imports: [
BrowserModule,
FormsModule, // <-- add this
ReactiveFormsModule // <-- and this
],
bootstrap: [ FormsDemoApp ]
})
class FormsDemoAppModule {}
在.angular-cli.json文件中加入一个全局样式
"styles": [
"assets/vendor/semantic.min.css",
"styles.css"
],
3、因为有多个form表单的例子,这里加上angular的路由,同样在app.module.ts下增加路由
import {RouterModule,Routes} from '@angular/router';
//...
import { AppComponent } from './app.component';
import { IntroComponent } from './intro/intro.component';
import { DemoFormSkuComponent } from './demo-form-sku/demo-form-sku.component';
const routes:Routes=[
{path:'',component:IntroComponent,pathMatch:'full'},
{path:'sku',component:DemoFormSkuComponent,pathMatch:'full'}
];
@NgModule({
declarations: [
AppComponent,
IntroComponent,
DemoFormSkuComponent
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpModule,
RouterModule.forRoot(routes)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
接着改写根组件的html,加上路由的router-outlet,即app.component.html文件
4、创建组件intro.component.ts和demo-form-sku.component.ts组件
ng g component intro
ng g component demo-form-sku
5、修改组件 demo-form-sku.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-demo-form-sku',
templateUrl: './demo-form-sku.component.html',
styleUrls: ['./demo-form-sku.component.css']
})
export class DemoFormSkuComponent implements OnInit {
constructor() { }
ngOnInit() {
}
onSubmit(form:any):void{
console.log('you submitted value:',form);
}
}
demo-form-sku.component.html
Demo Form:Sku
6、Using FormBuilder ng g component component demo-form-sku-with-builder
import { Component, OnInit } from '@angular/core';
import {FormBuilder,FormGroup} from '@angular/forms';
@Component({
selector: 'app-demo-form-sku-with-builder',
templateUrl: './demo-form-sku-with-builder.component.html',
styleUrls: ['./demo-form-sku-with-builder.component.css']
})
export class DemoFormSkuWithBuilderComponent implements OnInit {
myForm:FormGroup;
constructor(fb:FormBuilder) {
this.myForm=fb.group({
'sku':['ABC123']
})
}
ngOnInit() {
}
onSubmit(value:string):void{
console.log('you submitted value:'+value);
}
}
demo-form-sku-with-builder.component.html
Demo Form:Sku with Builder
备注:表单中使用了 [formGroup],如