Angular 6 FormArray和HTML循环

时间:2019-02-20 13:59:55

标签: angular ngfor angular-forms formarray

全部

我很难让FormArray与当前的应用程序一起使用。我正在尝试从服务中获取名称,并将其添加到预订表单中(并使用户能够添加/删除/修改名称)

以下是相关代码:

reservationForm: FormGroup;
attendeeArray: FormArray;

constructor(
  private groupMeetingService: GroupMeetingsService,
  private formBuilder: FormBuilder
) {}

ngOnInit() {
  this.initialize();
}

private createAttendeeName(name: string): FormControl {
  return this.formBuilder.control({
    name: name
  });
}

private initialize(): void {
  this.attendeeArray = this.formBuilder.array([]);
  this.reservationForm = this.formBuilder.group({
    attendeeRadio: ['inPerson'],
    attendeeName: this.attendeeArray,
  });

  this.groupMeetingService.getMeeting(this.meeting.id).subscribe(meeting => 
  {
    this.meetingLocation = meeting.location;
  });
  this.groupMeetingService
    .getReservations(this.meeting.id)
    .subscribe(data => {
      this.reservations = data;
      this.attendeeArray = this.getAttendeeNames();
      data.attendees.forEach(attendee => {
        this.attendeeArray.push(this.createAttendeeName(attendee.name));
      });
      console.log('array', this.reservationForm);
  });
}

当我查看控制台时,它确实表明正在添加它。上面的代码正确吗?

如果正确,我如何在HTML中循环浏览并显示它?

我尝试了很多事情,但是没有运气:-(

<div class="reservation-container" [formGroup]="reservationForm">
  <div formArraryName="attendeeArray" *ngFor="let attendee of reservationForm.controls['attendeeName'].controls; let i = index">
    <input [formControlName]="i" value="{{ attendee.name }}">
  </div>
</div>

Thx jonpfl

3 个答案:

答案 0 :(得分:0)

请考虑以下内容

    <div class="reservation-container" [formGroup]="reservationForm">
  <div formArraryName="attendeeArray" *ngFor="let attendee of reservationForm.get('attendeeName')['controls']; let i = index">
    <input [formControlName]="i" value="{{ attendee.name }}">
  </div>
</div>

答案 1 :(得分:0)

您有一个FormControl数组(而不是FormGroup数组)。所以

<div class="reservation-container" *ngIf="reservationForm" [formGroup]="reservationForm">
  <!--is attendeeName-->
  <div formArraryName="attendeeName">
    <!--the "formArrayName out of the *ngFor-->
    <div *ngFor="let attendee of reservationForm.controls['attendeeName'].controls; let i = index">
    <!--is formControl-->
    <input [formControl]="attendee" >
    </div>
  </div>
</div>
<!--only for check use-->
{{reservationForm?.value|json}}

答案 2 :(得分:0)

类似的事情应该起作用:

<div formArrayName="credentials" *ngFor="let creds of form.controls.attendeeName?.value; let i = index">
    <ng-container [formGroupName]="i">
      <input formControlName="name">
    </ng-container>
</div>

From this example