0

我正在尝试创建一个反应式表单,它将在页面上显示有关会议的详细信息,标签是动态的并从 API 返回。

这是返回数据的示例。

const meetings = [
  {
    id: 1,
    date: '06/07/2018',
    meetings: [
      {
        id: 1,
        name: 'meeting 1',
        times: [
          {
            id: 1,
            name: '1PM'
          },
          {
            id: 2,
            name: '2PM'
          }
        ]
      },
      {
        id: 2,
        name: 'meeting 2',
        times: [
          {
            id: 3,
            name: '3PM'
          },
          {
            id: 4,
            name: '4PM'
          }
        ]
      }
    ]
  },
  {
    id: 2,
    date: '07/07/2018',
    meetings: [
      {
        id: 3,
        name: 'meeting 3',
        times: [
          {
            id: 5,
            name: '8PM'
          },
          {
            id: 6,
            name: '9PM'
          }
        ]
      },
      {
        id: 4,
        name: 'meeting 4',
        times: [
          {
            id: 7,
            name: '10PM'
          },
          {
            id: 8,
            name: '11PM'
          }
        ]
      }
    ]
  }
];

这是我目前在我的 HTML 中的内容

<form [formGroup]="formf" novalidate (ngSubmit)="sub()">
  <div *ngFor="let meeting of meetings">{{meeting.date}}
    <div *ngFor="let details of meeting.meetings">{{details.name}}
      <div formArrayName="meetingTime">
        <div *ngFor="let timings of details.times; let i=index">
          <div class="form-group">
            <div formGroupName="{{i}}">
              <label for="selected">{{timings.name}}</label>
              <input formControlName="selected" class="form-control input-sm" type="checkbox" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <input type="submit" [disabled]="!formf.valid" value="Save" />
</form>

在我的组件中,我正在创建一个初始化为的表单模型

 initForm() {
    this.formf = this.formBuilder.group({
      meetingTime: new FormArray([])
    });
  }

当数据从 API 返回时,我尝试将其推送到 FormArray

setForm(meetingDate: MeetingDate[]) {
    let meetingTimeArray = <FormArray>this.formf.controls['meetingTime'];
    meetingDate.forEach(date => {
      date.meetings.forEach(app => {
        app.times.forEach(time => {
          meetingTimeArray.push(this.formBuilder.group({
            id: [time.id],
            selected: false
          }))
        });
      });
    });
  }

我在屏幕上打印了表单模型,当我单击复选框时,我可以看到它们仅更新前两个选定的值,我认为这是因为我已将 {{i}} 添加到 formGroupName 中,因此它们都映射到0, 1 个索引数组。

4

1 回答 1

0

我已经完成了这项工作,不确定这是否是最有效的方法,但它确实有效!

我没有在 *ngFor 上有索引,而是将它添加到我将控件推送到表单模型的打字稿中。

setForm(meetingDate: MeetingDate[]) {
let index = 0;

let meetingsArray = <FormArray>this.formf.controls['meetingTime'];
meetingDate.forEach(date => {
  date.meetings.forEach(app => {
    app.times.forEach(time => {
      meetingsArray.push(this.formBuilder.group({
        id: [time.id],
        selected: false
      }))
      time.index = index;
      index++;
    });
  });
});

this.meetings = meetingDate;
}
于 2018-07-14T08:41:53.857 回答