mercredi 10 janvier 2018

Auto select checkboxes from data within Form Array

I have a list of skills which is fetched from the DB like so:

  <div class="uk-margin">
  <div *ngFor="let data of skills">
    <div *ngFor="let skill of data.allSkills">
      <input type="checkbox"> <br>
    </div>
  </div>
</div>

The above outputs:

enter image description here

My form modal looks like this:

this.userForm = this._fb.group({
  name: ['', [Validators.required]],
  skills: this._fb.array([]),
});

I then fetch the checkbox values for the logged In user that they selected at some other time. As I am using Reactive Forms I patch the returned values from the DB for the user like so:

// Patch Skills
let ctrl = <FormArray>this.userForm.controls.skills;
  this.user.skills.forEach(item => {
    ctrl.push(new FormControl(item))
});

  // Patch Other things
   this.userForm.patchValue({
     name: this.user.name,
   });

If I console.log(ctrl.controls); I get the following:

I have a test
I have a nothing

How can I auto select the checkbox items that have been returned from the DB for that user (so that "I have a nothing" & "I have a test" are auto checked) and also update the formArray incase the user checks or unchecks values before sending it to the DB?




Aucun commentaire:

Enregistrer un commentaire