gpt4 book ai didi

Angular 2 : ReactiveForm Updating Model

转载 作者:太空狗 更新时间:2023-10-29 17:36:10 24 4
gpt4 key购买 nike

我有一个响应式(Reactive)表单,我想直接填充我的模型。

form.component.html

<form [formGroup]="personForm" (ngSubmit)="savePerson()">
<md-card class="app-input-section">
<md-input formControlName="personName" placeholder="Person Name"></md-input>
... many more fields
<button md-raised-button color="primary">Save</button>
</md-card>
</form>

form.component.ts

@Component({
selector: 'person',
template: 'form.component.html'
})

export class FormComponent implements OnInit {

person: Person;
formBuilder: FormBuilder;
personForm: FormGroup;

constructor(formBuilder: FormBuilder, personService: PersonService) {
this.person = new Person();
this.personForm = formBuilder.group({
personName: [this.person.personName, Validators.required],
... many more properties for form
});
}

ngOnInit() {
console.log('ngOnInit() called');
}

savePerson() {
this.person.personName = this.personForm.value.personName;
... many more properties set
this.personService.savePersontoDB(this.person);
}
}

savePerson() 函数中,我必须将值从 personForm FormGroup 复制到 Person 对象。对于少数属性,这很好,但是如果我有很多属性,这将是另一件需要管理的事情。我怎样才能简化这段代码,以便:

  1. personForm 值会在表单值更改时自动复制到 Person 对象。
  2. personForm 值会在用户按下“保存”按钮(随后调用 save() 函数)时自动复制到 Person 对象。这样,我意味着不必将所有单独的表单值复制到我的模型(人)对象。

实现这一目标的最佳方式是什么?有没有我可以使用的 helper ,或者比这更简单?

非常感谢

JT

最佳答案

在我的应用中,我这样做了:

 this.selectedPhysical = <Physical>this.physicalForm.value;

这将表单 ui 中的字段映射到基础对象。所以你可以:

this.person = <Person>this.personForm.value;
this.personService.savePersontoDB(this.person);

关于 Angular 2 : ReactiveForm Updating Model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39326618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com