在我的Angular 2组件中,我使用Formgroup
和18 AbstractControl
s。用户可以编辑从数据库加载的配置文件。
我想添加一个Reset
- 按钮,将表单重置为原始状态(显然)。但是,使用this.form.reset()
清除所有字段。我可以通过调用AbstractControl
重置FormGroup
中的特定reset({firstname: 'Jack'});
。
是否可以将FormGroup
重置的状态更改为?
答案 0 :(得分:1)
创建表单初始化函数,并在重置后调用它
component.html
<form [formGroup]="profileForm">
<input formControlName="firstname" class="form-control">
<button class="btn" type="submit">Submit </button>
<button class="btn" type="button" (click)="onReset()">Reset </button>
</form>
Component.ts
profileForm: FormGroup;
profile = {
firstname: 'name'
}
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.initForm();
}
initForm() {
this.profileForm = this.formBuilder.group({
firstname: [this.profile.firstname, Validators.required]
});
}
onReset() {
this.profileForm.reset();
this.initForm();
}
答案 1 :(得分:1)
如果您构建(或已构建)表单,profile
对象与表单组中的属性匹配,则可以调用:
this.profileForm.reset(this.profile);
例如:
profile = {firstname: 'first name'};
// ...
this.profileForm = this.formBuilder.group({
firstname: [this.profile.firstname],
});
// ...
this.profileForm.reset(this.profile)
使用模板:
<form [formGroup]="profileForm">
<input formControlName="firstname" />
</form>
<强> DEMO 强>