有没有办法从模型中自动创建一个 FormGroup? 如果我有一个具有多个属性的模型:
模型:人
firstName: string,
lastName: string,
street: string
country: string
....
我想用它创建一个简单的 FormGroup:
表单:表单组
firstName: FormControl,
lastName: FormControl,
street: FormControl,
country: FormControl
....
在我看来,为模型中的每个属性显式定义一个 FormControl/FormGroup/FormArray 似乎很“脏”:
formBuilder.group({
firstName: person.firstName,
lastName: person.lastName,
street: person.street,
country: person.country,
...
});
每次来自后端的 API 发生变化时,我都必须调整模型和表单映射。 是否有某种生成器可以帮助我自动映射/创建 FormGroup ?
最佳答案
formBuilder.group({});
person.forEach(
(prop) => {
formBuilder.addControl(prop , new FormControl(person[prop], Validators.compose([ Validators.required])));
}
);
这不是一个完整的解决方案,因为验证器肯定会针对每个属性进行更改。
关于angular - 模型驱动/ react 形式 : Auto mapping from Model to FormGroup ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44018191/