要在Angular 2中使用响应式表单模块,你需要按照以下步骤操作:
npm install @angular/forms
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
// other modules
ReactiveFormsModule
],
// other declarations
})
export class AppModule { }
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-login',
template: `
`
})
export class LoginComponent {
loginForm: FormGroup;
constructor() {
this.loginForm = new FormGroup({
username: new FormControl('', Validators.required),
password: new FormControl('', Validators.required)
});
}
submit() {
// handle form submission
}
}
这就是在Angular 2中使用响应式表单模块的基本步骤。你可以根据你的需求进行更多的自定义,例如添加更多的表单字段、自定义验证器等等。