0

How can I populate check boxes of a form group while in "Edit Mode"?

I am working on a project where I am making and editing workouts, then storing them to a database (using firebase at this current time). The workout creation worked flawlessly with the Angular template driven approach, but I am trying to add the functionality where I can edit an existing workout. Because of this, I have made the form reactive where depending on if I am in editMode (this mode is determined from the route params) or not, the information is either populated, or it isn't.

This works great for the basic string population, such as title and imagepath. Here, I am in editMode (coming from the route params) and things are populated accordingly:

populated formgroup

However, I also have checkboxes to be filled on this same form. I am using Material Theme for the checkboxes. Here's an example from a workoutphase selection:

<mat-form-field
  hideRequiredMarker
  appearance="fill"
  class="phase">
  <mat-label>Phase</mat-label>
  <mat-select multiple id="phase" name="phase" formControlName="phases">
    <mat-option value="Base 1">Base 1</mat-option>
    <mat-option value="Base 2">Base 2</mat-option>
    <mat-option value="Base 3">Base 3</mat-option>
    <mat-option value="Build 1">Build 1</mat-option>
    <mat-option value="Build 2">Build 2</mat-option>
    <mat-option value="Recovery">Recovery</mat-option>
    <mat-option value="Peak">Peak</mat-option>
    <mat-option value="Race">Race</mat-option>
    <mat-option value="Testing">Testing</mat-option>
  </mat-select>
</mat-form-field>

and how it appears when creating a workout (the problem is when trying to populate while in editMode): checkbox dropdown

This appears with a list dropdown that later returns an array of selected items to be added to the workouts.

With the reactive approach, I am trying to be able to populate the checkboxes as filled while being in editMode (or when the information is being pulled in). Is there a way to populate checkboxes? Or would I simply need to "re-check" which boxes I want while in edit mode?

So far I have tried using a new FormArray([]); that takes this array and populates everything as it should be. This gives me loads of errors related to the formGroup.

This form is in the WorkoutEditComponent found in app/features/workouts-page/workout-edit You can get to the edit form by clicking on any workout on the home view workouts page, then clicking edit button at the top.

Here is the stackblitz to this code. You can see that if you go to the side menu and select workouts, create workout, then there is a checkbox option and the dropdown works. But when you go through the workouts/edit, then the checkboxes are unable to populate. I have simplified and backtracked a bit on this stackblitz for the sake of simplicity of the problem. Any method used with the FormArray([]) seemed to make the problem worse.

Here is some more information:

I am initializing the form through my ngOnInit after checking whether or not I am in edit mode:

ngOnInit()     
 this.route.params.subscribe((params: Params) => {
    this.id = +params["id"];
    this.editMode = params["id"] != null;
    this.initForm();
  });
}

and the initForm():

private initForm() {
  let workoutImgPath = "";
  let workoutTitle = "";
  if (this.editMode) {
    const workout = this.workoutService.getWorkout(this.id);
    workoutTitle = workout.title;
    workoutImgPath = workout.imagePath;
    console.log(workout);
  }

 this.workoutForm = new FormGroup({
    title: new FormControl(workoutTitle, Validators.required),
    imgPath: new FormControl(workoutImgPath, Validators.required)
  });
}

Above is the currently working solution where only the image path and title are being added to the form whilst in edit mode.

Can these checkboxes also be populated from an array of items while editing an existing workout?

2
  • 1
    Jeremy, it's NOT formArray is only an array. yes, a FormControl can store an Array, e.g. const array=[1,3,5];control=new FormControl(array) and this is what you need put in you multiple select Commented Feb 19, 2020 at 8:01
  • Thank you very much for clearing the confusion there. Knowing that made this much easier Commented Feb 19, 2020 at 19:06

2 Answers 2

1

I updated your stackblitz example, and hopefully managed to do what you are trying to do, it was quite simple actually.

https://stackblitz.com/edit/github-qzxhec-lnaozw

Sign up to request clarification or add additional context in comments.

3 Comments

Wow, quite simple indeed. I was trying to make a form array instead of just letting Angular know that it is an array. Thank you so much for the help!
No problem, glad I help, sometimes a simple solution is a right solution.
Code should be on this site, not on an external site.
1

Hope this helps, In edit mode patch the list of phases to the formcontrol.

HTML

<form>
<div>
    <button class="btn btn-primary" (click)="onEdit()">Edit</button>
</div>
<div style="margin-top: 100px;">
    <mat-form-field>
        <mat-label>Phases</mat-label>
        <mat-select [formControl]="phases" multiple>
            <mat-option value="Base 1">Base 1</mat-option>
            <mat-option value="Base 2">Base 2</mat-option>
            <mat-option value="Base 3">Base 3</mat-option>
            <mat-option value="Build 1">Build 1</mat-option>
            <mat-option value="Build 2">Build 2</mat-option>
            <mat-option value="Recovery">Recovery</mat-option>
            <mat-option value="Peak">Peak</mat-option>
            <mat-option value="Race">Race</mat-option>
            <mat-option value="Testing">Testing</mat-option>
        </mat-select>
      </mat-form-field>
</div>

TS

phases = new FormControl();


constructor() { }



 ngOnInit() {
    this.phases.valueChanges.subscribe(data => {
      console.log('Selected Options', data)
    });
  }



onEdit() {
    this.phases.patchValue(["Base 1", "Build 1"])
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.