一、使用模版式表单
把 HTML 表单控件(比如
<input>
和<select>
)放进组件模板中,并用ngModel
等指令把它们绑定到组件中数据模型的属性上。
你不用自己创建 Angular 表单控件对象。Angular 指令会使用数据绑定中的信息创建它们。 你不用自己推送和拉取数据。Angular 使用 ngModel
来替你管理它们。 当用户做出修改时,Angular 会据此更新可变的数据模型。
因此,ngModel
并不是 ReactiveFormsModule
模块的一部分。
虽然这意味着组件中的代码更少,但是模板驱动表单是异步工作的,这可能在更高级的场景中让开发复杂化。
二、代码示例
//新建项目
ng new form-test
//新建模板表单组件
ng g component form1
//app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { Form1Component } from './form1/form1.component';
import {FormsModule} from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
Form1Component
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
//app.component.html
<app-form1></app-form1>
//form1.compontent.html
<form #myForm = "ngForm" (ngSubmit) = "onSubmit(myForm.value)">
<div>用户名:<input #userName="ngModel" ngModel type="text" name="username"/></div>
<div ngModelGroup="passwordGroup">
<div>密码:<input ngModel type="password" name="password"/></div>
<div>确认密码:<input ngModel type="password" name="confirmPass"/></div>
</div>
<div>电话:<input ngModel type="text" name="mobile"/></div>
<div><input type="submit" value="提交"/></div>
</form>
<div>
{{userName.value}}
</div>
//form1.compontent.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-form1',
templateUrl: './form1.component.html',
styleUrls: ['./form1.component.css']
})
export class Form1Component implements OnInit {
constructor() { }
ngOnInit() {
}
onSubmit(value) {
console.log(value);
}
}
运行结果:

#myForm
是模板变量,myForm变量可以自定义,但是如果是表单文件,#myForm后面的值'ngForm'
是固定的。
ngModelGroup
让 form表单的数据化。
网友评论