Wednesday, 21 August 2019

How to add checked and unchecked checkboxes data to Firebase

I have an Array of objects as starter data in my Ionic 3 app:

public interesses = [
    { name: 'Viagens', checked: false  },
    { name: 'Animais', checked: false  },
    { name: 'Teatro', checked: false  },
    { name: 'Outros', checked: false  }
  ];

I am trying to create multiple checkboxes from this array, and add in Firebase all data, including checked and unchecked items from this list.

For now, my .ts code is:

interessesG :any = [];
profileForm: FormGroup;

  constructor(public navCtrl: NavController, 
    public navParams: NavParams, 
    private afAuth: AngularFireAuth, 
    public db: AngularFireDatabase,
    public fb: FormBuilder) {

      this.profileForm = fb.group({
        interesses: new FormArray([])
      });
  }

checado(data, i, isChecked: boolean) {
    this.interessesG = <FormArray>this.profileForm.controls.interesses;

    if (isChecked) {
      this.interessesG.push(new FormControl({name: data.name, checked: true}));
      console.log(this.interessesG.value);
    } else {
      let index = this.interessesG.controls.findIndex(x => x.value == data)
      this.interessesG.removeAt(index);
      console.log(this.interessesG.value);
    }
  }

saveProfile(){
    this.db.object('users/' + this.userId).update({     
      interesses:   this.interessesG.value        
    }).then(() => {
      console.log("Success!");
      }, error => {
        console.error(error);
      }
    );
  }

And my .html file:

<div formArrayName="interesses">
  <ion-item class="int-list" no-lines *ngFor="let int of interesses; let i = index">
    <ion-label></ion-label>
    <ion-checkbox slot="end" (ionChange)="checado(int, i, $event.checked)"></ion-checkbox>
  </ion-item>
</div>

With this code, I get only the checked item (which displays on console):

0: {name: "Animais", checked: true}

But I need to get something like this:

0: { name: 'Viagens', checked: false  },
1: { name: 'Animais', checked: true  },
2: { name: 'Teatro', checked: false  },
3: { name: 'Outros', checked: false  }

How can I do this?



from How to add checked and unchecked checkboxes data to Firebase

No comments:

Post a Comment