- 导入
FormControl:
import { FormControl } from '@angular/forms';
在 Component 里创建一个
name 实例,类型为
FormControl:

name = new FormControl('Jerry');
通过构造函数
FormControl 设置初始值。
- 在 HTML 文件里,将 element 同 Component 的
name属性建立绑定关系:


这之后 Component name 属性的值,就会自动传递到 HTML element 里:

这样,表单控件和 DOM 元素就可以互相通讯了:视图会反映模型的变化,模型也会反映视图中的变化。
使用
.value 可以访问 FormControl 实例的值:
显示控件的值: {{ name.value }}

如何使用
setValue 修改 FormControl 的值

updateName() {
this.name.setValue('Nancy');
}
点击按钮之后:

值变为 nancy:

在 event handler 里看到 click 响应事件在
zone.js 里的统一处理:


最终在
core.js 里调用
executeListenerWithErrorHandling:

执行 setValue:


如何响应用户输入
constructor(){
this.name.valueChanges.subscribe(selectedValue => {
console.log('value changed: ', selectedValue);
})
}
效果:

从调用栈发现,仍然是
executeListenerWithErrorHandling:


通过
EventEmitter 发送更新:

ng-untouched ng-pristine ng-valid 这三个 class 什么时候赋的值?

- ng-untouched The field has not been touched yet
- ng-pristine The field has not been modified yet
- ng-valid The field content is valid
如何使用表单组
form group
在 Component 里创建一个类型为
FormGroup 的属性。

其构造函数是一个 json 对象,property 的类型为
FormControl.

FormGroup 也能使用
setValue 等方法。
这个表单组还能跟踪其中每个控件的状态及其变化,所以如果其中的某个控件的状态或值变化了,父控件也会发出一次新的状态变更或值变更事件。
如何把 FormGroup 属性绑定到 HTML 文件中:

由
FormControlName 指令提供的
formControlName 属性把每个输入框和
FormGroup 中定义的
表单控件绑定起来。
FormGroup 组内数据一样可以通过
valueChanges 被监控:

this.profileForm.valueChanges.subscribe(
value => {
console.log('group value: ', value);
}
);
使用
setValue 修改 group 的值:

this.profileForm.setValue(
{
firstName: 'Tom',
lastName: "Tom1"
}
);
form 标签所发出的 submit 事件是内置 DOM 事件,通过点击类型为 submit 的按钮可以触发本事件。这还让用户可以用回车键来提交填完的表单。
往表单的底部添加一个 button,用于触发表单提交。

onSubmit(){
console.warn(this.profileForm.value);
}