angularformsangular-dynamic-forms

Dynamic forms including patching


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.


Solution

  • 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