4

I have firebase (realtime database) simple structure like this: enter image description here

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?

1
  • can you show the output of the line console.log(this.arrData) ? Commented Apr 18, 2018 at 9:38

2 Answers 2

1

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; } }); }); } 
Sign up to request clarification or add additional context in comments.

Comments

0

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}); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.