今天完成的事情:
响应式表单
响应式表单提供了一种模型驱动的方式来处理表单输入,其中的值会随时间而变化
制作表单
添加基础表单控件:
添加表单控件
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
// other imports ...
ReactiveFormsModule
],
})
export class AppModule { }
生成新文件
ng generate component NameEditor
导入 FormControl 类
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-name-editor',
templateUrl: './name-editor.component.html',
styleUrls: ['./name-editor.component.css']
})
export class NameEditorComponent {
name = new FormControl('');
}
在模板中注册该控件,name-editor.component.html中
<label>
Name:
<input type="text" [formControl]="name">
</label>
显示该组件,在app.component.html 添加
<app-name-editor></app-name-editor>
显示表单控件的值,name-editor.component.html中
<p>
Value: {{ name.value }}
</p>
替换表单控件的值,在name-editor.component.ts中
updateName() {
this.name.setValue('Nancy');
}
修改模板
<p>
<button (click)="updateName()">Update Name</button>
</p>
把表单控件分组
生成一个 ProfileEditor 组件并从 @angular/forms 包中导入 FormGroup 和 FormControl 类
ng generate component ProfileEditor
import { FormGroup, FormControl } from '@angular/forms';
新文件添加profile-editor.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-profile-editor',
templateUrl: './profile-editor.component.html',
styleUrls: ['./profile-editor.component.css']
})
export class ProfileEditorComponent {
profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
});
}
模型关联到视图
profile-editor.component.html 中
<form [formGroup]="profileForm">
<label>
First Name:
<input type="text" formControlName="firstName">
</label>
<label>
Last Name:
<input type="text" formControlName="lastName">
</label>
</form>
onSubmit() 回调方法添加为 form 标签上的 ngSubmit 事件监听器,修改
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
ProfileEditor 组件上的 onSubmit() 方法会捕获 profileForm 的当前值
onSubmit() {
// TODO: Use EventEmitter with form value
console.warn(this.profileForm.value);
}
创建嵌套的表单组 profile-editor.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-profile-editor',
templateUrl: './profile-editor.component.html',
styleUrls: ['./profile-editor.component.css']
})
export class ProfileEditorComponent {
profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
address: new FormGroup({
street: new FormControl(''),
city: new FormControl(''),
state: new FormControl(''),
zip: new FormControl('')
})
});
}
修改视图模板,profile-editor.component.html
<div formGroupName="address">
<h3>Address</h3>
<label>
Street:
<input type="text" formControlName="street">
</label>
<label>
City:
<input type="text" formControlName="city">
</label>
<label>
State:
<input type="text" formControlName="state">
</label>
<label>
Zip Code:
<input type="text" formControlName="zip">
</label>
</div>
明天的计划:
构建动态表单
评论