1:在AppModule模块中引入ReactiveFormsModule要使用响应式表单,请从@angular/forms包中导入ReactiveFormsModule并将其添加到NgModule的导入数组中。import{ReactiveFormsModule}from'@angular/forms';@NgModule({imports:[//otherimports...ReactiveFormsModule],})exportclassAppModule{}2:创建新组件nggcNameEditor3:请输入组件在FormControl类中导入FormControl类是角度响应式表单最基本的构造块。要注册单个表单控件,请在组件中导入FormControl类,创建一个新的FormControl实例,并将其保存在属性中。从'@angular/core'导入{Component};从'@angular/forms'导入{FormControl};@Component({选择器:'app-name-editor',templateUrl:'./name-editor.component.html',styleUrls:['./name-editor.component.css']})exportclassNameEditorComponent{name=newFormControl('');}4:在组件模板中注册一个表单控件修改模板,是一个表单control添加formControl绑定,formControl由ReactiveFormsModule中的FormControlDirective提供。
值:{{name.value}}
使用此模板绑定语法,将表单控件注册到模板中名为name的输入元素。这样,表单控件和DOM元素就可以相互通信:视图将反映模型的变化,而模型将反映视图的变化。5:替换表单控件的值FormControl提供了一个setValue()方法,该方法会修改表单控件的值。jsupdateName(){this.name.setValue('南希');}html值:{{name.value}}
在这个例子中,你只使用了单个控件FormControl,但是当调用FormGroup或者使用FormArray的setValue()方法时,传入的值必须匹配结构体控制组或控制阵列。6:组窗体控件。FormControl实例可以控制单个输入框对应的控件,FormGroup可以控制一组FormControl实例。创建FormGroup时,每个控件将按名称跟踪1>:创建新组件nggcProfileEditor2>:导入FormGroup和FormControl类并创建FormGroup实例import{Component}from'@angular/core';import{FormGroup,FormControl}来自'@angular/forms';@Component({selector:'app-profile-editor',templateUrl:'./profile-editor.component.html',styleUrls:['./profile-editor.component.css']})exportclassProfileEditorComponent{profileForm=newFormGroup({firstName:newFormControl(''),lastName:newFormControl(''),});}现在这些单独的控件FormControl被收集到一个控件组中FormGroup,FormGroup实例与FormControl实例具有相同的属性(如value,untouched)和方法(如setValue())3>:与FormGroup关联的模型和视图可以跟踪每个单独控件的状态和变化FormControl,如果其中一个控件的状态或值改变时,父控件也会有新的状态改变或值改变事件profileForm通过[formGroup]指令,在模型和表单FormControlName命令的输入框之间创建了一个通信层,FormControlName命令提供的formControlName属性将每个输入框与FormGroup中定义的表单控件绑定在一起。4>:关联FormGroup的model和viewhtmljsonSubmit(){console.warn(this.),lastName:newFormControl(''),address:newFormGroup({street:newFormControl(''),city:newFormControl(''),state:newFormControl(''),zip:newFormControl('')})});html