Search code examples
javascriptfirebase-realtime-databaseionic3angularfire2

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>{{int.name}}</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?


Solution

  • You can directly change the existing array to get all the object values in an array.

    checado(data, i, isChecked: boolean) {
        let newObj = data;
        newObj.checked = isChecked;
        this.interesses[i] = newObj;
        console.log(this.interesses);
    }
    

    If you want only the objects use the following.

    console.log(...this.interesses);
    

    I have created a stackblitz example with your code. https://stackblitz.com/edit/ionic-58mfcp

    Hope it helps.