【问题标题】:Angular form gathering data in wrong formatAngular 表单以错误的格式收集数据
【发布时间】:2018-11-05 18:50:31
【问题描述】:

我有来自 json 服务器的数据,它完全按照我想要和期望的方式显示,但是在保存更改时,它并没有以它传入的相同格式保存。

这是我的表格:

<form (ngSubmit)="saveProfile(form.value, form.valid)" #form="ngForm" novalidate>
  ...
  <input 
    matInput 
    placeholder="Company Name" 
    type="text"
    name="companyName"
    required
    #companyName="ngModel"
    [ngModel]="profile?.companyName">

  <!-- Code in question below: -->
  <ul class="days-of-operation">
    <li *ngFor="let day of profile?.daysOfOperation">
      <mat-checkbox
        [name]="day.day"
        [ngModel]="day.open">
        {{day.day}}
      </mat-checkbox>
    </li>
  </ul>
  ...
  <button type="submit" [disabled]="form.invalid">
    Update Profile
  </button>
</form>

这是进来的工作 JSON:

{
  "profile": {
  "companyName": "Example Company",
    "daysOfOperation": [
      {
        "day": "Sunday",
        "open": false
      }, {
        "day": "Monday",
        "open": true
      }, {
        "day": "Tuesday",
        "open": true
      }, {
        "day": "Wednesday",
        "open": true
      }, {
        "day": "Thursday",
        "open": true
      }, {
        "day": "Friday",
        "open": true
      }, {
        "day": "Saturday",
        "open": true
      }
    ],
    ...
  }
}

这是当我单击更新按钮时form.value 发送给saveProfile 方法的数据:

{
  "companyName": "Example Name",
  "Sunday": false,
  "Monday": true,
  "Tuesday": true,
  "Wednesday": true,
  "Thursday": true,
  "Friday": true,
  "Saturday": false
}

如您所见,表单以完全不同的格式收集数据。这适用于companyName。我可以将它更改为我想要的任何东西,保存它,它会以我保存它的方式返回,但是这些日子不再在 daysOfOperation 对象中传递。为什么表单发送的数据与传入的数据不同?如何让它以与进来时相同的格式保存?我做错了什么?

如果这会让事情变得更好/更容易,我愿意改变我的运营日期格式。

【问题讨论】:

    标签: angular angular-material ngfor angular-forms json-server


    【解决方案1】:

    您可以简单地绑定到现有对象,而不是使用form.value,然后使用this.profile

    像这样更改ngModel

      <mat-checkbox
        [name]="day.day"
        [(ngModel)]="day.open">
        {{day.day}}
      </mat-checkbox>
    

    在您的saveProfile 中,只需使用this.profile,如下所示:

    saveProfile() {
      console.log(this.profile)
    }
    

    Here is a StackBlitz example

    【讨论】:

    • 我正在尝试维护单向数据流并在我准备好保存更改时发出事件。有没有一种简单的方法可以使用 for 循环中的复选框来做到这一点?
    猜你喜欢
    • 2012-06-29
    • 1970-01-01
    • 2018-01-25
    • 2018-01-16
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    • 1970-01-01
    相关资源
    最近更新 更多