EPaz
EPaz

Reputation: 95

Fill formArray for checkbox input if the model already has checked values (Angular 8)

I am trying to populate an Angular form with information I already have on my database. I got it working for input 'range' and 'text', but I cannot figure out how to do it for 'checkbox'.

Here is an example of what I have:

this.form = this.fb.group({
      option: this.fb.group({
        numbers: this.fb.array([]),
        name: ['', Validators.required]
      }),
selectedCount = 0;
maxCount = 3;
preference = {
    options: ['West',
      'East',
      'Midwest',
      'Southwest',
      'Southeast',
      'Northeast']
  };
inArray(option: string) {
    const formArray = this.form.get('option').get('numbers') as FormArray;
    return formArray.value.includes(option);
  }

onChange(option: string, isChecked: boolean) {
    const formArray = this.preferencesForm.get('option').get('numbers') as FormArray;
    if (isChecked) {
      formArray.push(new FormControl(option));
      this.selectedCount++;
    } else {
      const index = formArray.controls.findIndex(x => x.value === option);
      formArray.removeAt(index);
      this.selectedCount--;
    }
  }

<div formGroupName="option">

    <div *ngFor="let option of preference.options">
        <input  
          type="checkbox" 
          (change)="onChange(option, $event.target.checked)"
          [disabled]="(selectedCount >= maxCount) && !inArray(option)"
          id={{option}}, name={{option}}>
        <label for='{{option}}'> {{option}} </label>
      </div>
    </div>

    <input type="text" name="name" id="name" required formControlName="name">

  </div>
</div>

Finally, this is how I am trying to populate my form. I have userPref that has the information from the backend. I am able to populate the 'text' input field, but I cannot get the checkboxes

populateInfo() {
    const formControls = this.form.controls;
    const userPref = this.user.user_pref;  

    console.log('user ', userPref);
    console.log('pref form ', preferenceFormControls)

    formControls.option.get('name').setValue(userPref.name);
    userPref.numbers.forEach( (num) => {
      (formControls.option.get('numbers') as FormArray).push( this.fb.control(num) )
    });
  }

This correctly populates 'name' with the userPref info (showing I am pulling the information correctly) This adds to the form array the userPref numbers. I can see that on the browser terminal. However, I have no idea on how to show the box checked.

This is a long post, so thanks beforehand!

Upvotes: 0

Views: 1902

Answers (1)

Riccardo Gai
Riccardo Gai

Reputation: 421

Your idea is a bit complicated. Hope this helps:

const dataFromBE = .... // get the data from BE
this.form = this.fb.group({
    numbers: new FormArray(this.preference.options.map(x => dataFromBE.includes(x))),
    name: new FormControl('', [Validators.require]),
});

in the HTML:

<div formArrayName="numbers">
  <input  
      *ngFor="let opt of form.get('numbers').controls; let i = index"
      [formControlName]="i"
      type="checkbox" 
   />
    <label> {{preference.option[i]}} </label>
</div>

finally when you submit the form you get the data:

const value = this.form.get('numbers').value as [];
//value is an array of boolean, but if you need the value see below
console.log(value.map((x, i) => x ? this.preference.options[i] : null).filter(x => x))

Upvotes: 1

Related Questions