jonpfl
jonpfl

Reputation: 105

Angular 6 FormArray and looping in HTML

All,

I am having a really hard time getting FormArray working with my current application. I am trying to get names from a service and add them to a reservation form (and give the ability to the user to add/delete/modify names)

Here is relevant code:

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);
  });
}

When I look at my console, it does show that it is being added. Is the above code correct?

And if it is correct, how do I loop through it in HTML and get it to display?

I have tried a bunch of things but no luck :-(

<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

Upvotes: 2

Views: 7689

Answers (2)

Josejacob99
Josejacob99

Reputation: 525

Consider the following

<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>

Upvotes: 5

Eliseo
Eliseo

Reputation: 57929

You has an array of FormControl (not an array of FormGroup). so

<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}}

Upvotes: 1

Related Questions