加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 2:ReactiveForm更新模型

发布时间:2020-12-17 17:35:41 所属栏目:安全 来源:网络整理
导读:我有一个反应形式,我想直接填充我的模型. 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 fie
我有一个反应形式,我想直接填充我的模型.

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对象.对于少数几个属性,这很好,但如果我有很多属性,这将是另一件需要管理的事情.如何简化此代码以便:

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

实现这一目标的最佳方法是什么?我可以使用某种助手还是比这更简单?

非常感谢

JT

解决方法

在我的应用程序中,我做到了这一点:

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

这将ui形式的字段映射到底层对象.所以你可以:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读