0

I have a form to update existing/create new users. One of the fields is an array of activities they can participate in. The list of activities is retrieved from the server. When editing a user, I want to display all possible activities in a form (checkboxes) and also mark the ones the user has chosen.

However, I'm having troubles with getting this to work. I have read the following blog posts: https://netbasal.com/angular-reactive-forms-the-ultimate-guide-to-formarray-3adbe6b0b61a https://jasonwatmore.com/post/2020/09/18/angular-10-dynamic-reactive-forms-example

As a result, I came up with something like this:

component.ts:

form: FormGroup = this.fb.group({
    firstName: ['', Validators.required],
    lastName: ['', Validators.required],    
    activities: this.fb.array([]),
  });

  activitiesForm$ = this.activitiesService.allActivities$.pipe(
    tap((activities) => {
      for (let activity of activities) {
        this.t.push(this.fb.group({ id: ['', Validators.required] }))        
      }
    }),
  );

And in my template:

<div *ngIf="activitiesForm$ | async as activities">    
    <div *ngFor="let activity of activities">
      <input class="form-check-input" type="checkbox" role="switch" formControlName="activity">
    </div>
  </div>

I understand why this doesn't work. However, I don't understand what to do to get this working.

R. Richards
  • 24,603
  • 10
  • 64
  • 64
TomDS
  • 49
  • 4

1 Answers1

1

I created this stackblitz app for you to show you the solution for your problem

https://stackblitz.com/edit/angular-ivy-r2xaua?file=src/app/app.component.html

Ahmed Shehatah
  • 658
  • 5
  • 11
  • Thank you for the stackblitz! It's not 100% what I was looking for, but I think it should work starting from your input. The list of activities can be longer than the activities the user is already subscribed for. In your example, I'd probably need to use combineLatest together with map to build the userActivities array. – TomDS Mar 10 '22 at 12:18