Reputation: 324
I have firebase (realtime database) simple structure like this:
Listing all items in view:
<ion-list>
<ion-item *ngFor="let item of arrData; let i = index" (click)="delete(item)">
{{i+1}}. {{item.name}}<small> - {{item.address}}</small>
</ion-item>
</ion-list>
In controller the database is defined, because showing and adding data is working:
arrData = []
constructor(public navCtrl: NavController, private fdb: AngularFireDatabase) {
this.fdb.list("/schools/").valueChanges().subscribe(data =>{
this.arrData = data;
console.log(this.arrData);
})
btnAddClicked(){
this.fdb.list("/schools/").push({name:this.schoolName, address:this.schoolAddress});
}
I want to delete item when it is selected (clicked). From documentation I understand that it is possible to use .remove(), just need path to item. But for that I need to get that auto-generated key. How to get that? Or is there another way to remove selected item?
Upvotes: 4
Views: 7182
Reputation: 1467
I think there is something you need to take in the code. I took to your code snippet to address my concern. The line chval = childSnapshot.val(); should changed to chval =childSnapshot.val with the parenthesis.
deleteNote(key){
// var db = this.fdb.database.ref();
var query = firebase.database().ref('todo').orderByKey();
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var pkey = childSnapshot.key;
var chval = childSnapshot.val;
console.log(childSnapshot.val);
//check if remove this child
if(chval.note == key.note && chval.date == key.date){
firebase.database().ref().child("todo/"+pkey).remove();
return true;
}
});
});
this.state.noteArray.splice(key, 1);
this.setState({noteArray: this.state.noteArray});
}
Upvotes: 0
Reputation: 324
Thanks to this post, found solution. Maybe not the prettiest, but works:
delete(item){
var db = this.fdb.database.ref();
var query = this.fdb.database.ref("schools").orderByKey();
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var pkey = childSnapshot.key;
var chval = childSnapshot.val();
//check if remove this child
if(chval.name == item.name && chval.address == item.address){
db.child("schools/"+pkey).remove();
return true;
}
});
});
}
Upvotes: 1