要使用Angular CLI创建响应式表单,可以按照以下步骤进行:
npm install -g @angular/cli
ng new my-app
cd my-app
ng generate component my-form
my-form.component.ts
,并添加以下代码:import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-my-form',
templateUrl: './my-form.component.html',
styleUrls: ['./my-form.component.css']
})
export class MyFormComponent {
myForm: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.myForm = this.formBuilder.group({
name: '',
email: '',
password: ''
});
}
onSubmit() {
console.log(this.myForm.value);
}
}
my-form.component.html
,并添加以下代码:
app.module.ts
中导入和添加ReactiveFormsModule
模块:import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { MyFormComponent } from './my-form/my-form.component';
@NgModule({
declarations: [
AppComponent,
MyFormComponent
],
imports: [
BrowserModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
http://localhost:4200
:ng serve
现在,你应该能够在浏览器中看到一个包含输入字段和提交按钮的表单。当你填写表单并点击提交按钮时,表单的值将打印到控制台上。
这就是使用Angular CLI创建响应式表单的基本步骤和示例代码。你可以根据自己的需求进行修改和扩展。
下一篇:Angular CLI 终止。