I have a set of objects that I am using as initial data in my Ionic 3 application:
public interests = [
{ name: 'Travel', checked: false },
{ name: 'Animals', checked: false },
{ name: 'Theatre', checked: false },
{ name: 'Others', checked: false }
];
My goal is to create multiple checkboxes based on this array, and store all the data, including both checked and unchecked items, in Firebase.
Currently, my TypeScript code looks like this:
selectedInterests :any = [];
profileForm: FormGroup;
constructor(public navCtrl: NavController,
public navParams: NavParams,
private afAuth: AngularFireAuth,
public db: AngularFireDatabase,
public fb: FormBuilder) {
this.profileForm = fb.group({
interests: new FormArray([])
});
}
checkItem(data, i, isChecked: boolean) {
this.selectedInterests = <FormArray>this.profileForm.controls.interests;
if (isChecked) {
this.selectedInterests.push(new FormControl({name: data.name, checked: true}));
console.log(this.selectedInterests.value);
} else {
let index = this.selectedInterests.controls.findIndex(x => x.value == data)
this.selectedInterests.removeAt(index);
console.log(this.selectedInterests.value);
}
}
saveProfile(){
this.db.object('users/' + this.userId).update({
interests: this.selectedInterests.value
}).then(() => {
console.log("Success!");
}, error => {
console.error(error);
}
);
}
And here is my HTML file:
<div formArrayName="interests">
<ion-item class="interest-list" no-lines *ngFor="let interest of interests; let i = index">
<ion-label>{{interest.name}}</ion-label>
<ion-checkbox slot="end" (ionChange)="checkItem(interest, i, $event.checked)"></ion-checkbox>
</ion-item>
</div>
Currently, only the checked item is showing up in the console:
0: {name: "Animals", checked: true}
But what I actually need is something like this:
0: { name: 'Travel', checked: false },
1: { name: 'Animals', checked: true },
2: { name: 'Theatre', checked: false },
3: { name: 'Others', checked: false }
How can I achieve this?