【问题标题】:Angular Reactive Forms: Save data in a model on form submitAngular Reactive Forms:在表单提交时将数据保存在模型中
【发布时间】:2020-03-08 02:14:38
【问题描述】:

我正在研究角度反应形式。我使用模型如context 在表单中填写初始值,类似这样

this.form = this.formBuilder.group({
    name: [this.context.name],
    age: [this.context.age],
    place: [this.context.place],
    school: [this.context.school]
  });

我想在表单提交时将数据存储回context 模型。我正在做这样的事情。有什么优雅的方法可以做到这一点。

this.context.name = this.form.value.name;
this.context.age= this.form.value.age;
this.context.place= this.form.value.place;
this.context.school= this.form.value.school;

【问题讨论】:

    标签: angular angular-reactive-forms


    【解决方案1】:

    只需使用以下代码,它就会将所有表单值分配给您的对象。

    this.context= Object.assign(this.context, this.form.value);

    【讨论】:

      【解决方案2】:

      可能是这样的:

      this.form.getRawValue().name
      

      或者即使您的表单与您的 Context 接口匹配,它也可能是这样的:

       const context = this.form.getRawValue() as Context;
      

      【讨论】:

        猜你喜欢
        • 2019-04-10
        • 2021-11-13
        • 2017-10-01
        • 2022-01-25
        • 2020-07-31
        • 2020-12-19
        • 2016-05-07
        • 2019-06-24
        • 1970-01-01
        相关资源
        最近更新 更多