有两种方法可以执行您所说的操作,一种方法涉及在创建表单时填充字段,另一种涉及在创建表单后添加值。前者似乎适合您在这里想要做的事情,而后者适用于根据计算值或服务调用的合并构建表单。
在对响应式表单进行任何操作之前,请确保您已经ReactiveFormsModule
在模块中导入了 ,如下所示:
imports: [
ReactiveFormsModule
]
第一种方式
创建包含值的表单(即“编辑”)
首先,在 component.ts 中创建表单,如下所示:
export class YourEditComponent implements OnInit {
// First you'll specify your form variable
form: FormGroup;
// In your constructor, be sure to inject FormBuilder
constructor (private formBuilder: FormBuilder) {}
// I like to create the form in OnInit, but for testing
// purposes I prefer to call a function that creates the form,
// rather than doing the logic in this function
ngOnInit(): void {
this.createEditFormGroup();
}
// Here's where you create your form. I assume you'll
// be getting your form data object from a service, but
// for the sake of demonstration I'll create the object here
createEditFormGroup(): void {
// Here you'll have the object already, so don't do this
const thread = {
author: 'breadman0',
email: 'breadman0@gmail.com'
}
// Now simply create the form, passing this object (in this
// case, the object "thread")
this.form = this.formBuilder.group(thread);
}
// Now when you save, you don't need to pass in the value, you
// can just access the form's value
save(): void {
console.log(this.form.value);
}
}
在您的 component.html 中,您只需要添加一些指令并处理“提交”事件。请参阅下面的 html,修改为可以工作:
<form [formGroup]="form" (ngSubmit)="save()">
<div class="form-group">
<label for="author">Author of thread:</label>
<input
formControlName="author"
class="form-control"
required
type="text">
</div>
<div class="form-group">
<label for="email">Author's email:</label>
<input
formControlName="email"
class="form-control"
required
type="text">
</div>
</form>
请注意,“必需”并不是很有帮助,因为可以在 devtools 中进行修改。您最好按照表单中的要求设置字段。
第二种方法
用值填充现有表单
这种方式非常相似,除了我们只是用我们正在使用的任何对象的新实例创建表单
this.form = this.formBuilder.group({
author: '',
email: ''
});
//or
this.form = this.formBuilder.group(new Thread());
然后稍后我们调用patchValue:
// This can be done for any field in the form. I choose "author" here
this.form.patchValue({author: 'anonymous'});