Reputation: 105
When i insert data(using push() method) into the firebase it generates a random key as shown in image. I am able to update key values(name and age) using random number(-LExEhDWjwXcj6rGZar9)
Now what i want to achieve is, i want to update key values(name:"Manjeshwar" age:"27" to name:"somename" age:"20") without using **-LExEhDWjwXcj6rGZar9 random key**. i want to update it dynamically.
Upvotes: 0
Views: 2940
Reputation: 105
After a lot of research i got the answer to my own question. Answer: To get the key just use "$key" in Angular2 so you can update values of any random key you want to update as shown in below code.
Component.html:
<div class="employees" *ngFor="let e of employees | async">
<ul>
<li>Name: {{e.name }}</li>
<li>Age: {{e.age}}</li>
<li>Random Key: {{e.$key }}</li> //outputs random key
<button class="btn btn-primary" (click)="goToDetails(e, '$key')">Edit</button>
</ul>
</div>
//form to update the values
<div id="uform" class="col-md-4" hidden>
<input class="form-control col-md-3" type="text" placeholder="Name" id="uname" name="name">
<input class="form-control col-md-3" type="number" placeholder="Age" id="uage" age = "age">
<button class="btn btn-primary" (click) = update()>Update</button>
</div>
Component.ts:
//Function to get id of form
getInputVal(id){
return (<HTMLInputElement>document.getElementById(id)).value;
}
fbkey:string = ''; //global variable
goToDetails(employees:{},key:string) {
this.fbkey = employees[key];
document.getElementById("uform").style.display = "block";
}
update(){
//Get Values
var name =this.getInputVal('uname');
var age= this.getInputVal('uage');
this.updateF(name, age);
}
updateF(name, age){
this.af.database.object('employees/'+this.fbkey).set({
name: name,
age: age
})
}
So using "$key" we can dynamically update the values of that specific key.
Upvotes: 0
Reputation: 598708
To get the key, you must know something under that key. Say that you know the name of the user, then you can query all users with that name and update them:
var ref = firebase.database().ref("employees");
ref.orderByChild("name").equalTo("manjeshwar s").once("value", function(snapshot) {
snapshot.forEach(function(employee) {
employee.ref.update({ age: "20" });
});
});
Note that if there are multiple employees with this name, all of them will be updated.
If employee names are unique, consider actually using those as the key for each employee node:
employees
"manjeshwar s": {
...
}
"puf": {
...
}
With this structure, you are guaranteed that employee names are unique. And you can update them without a query:
ref.child("manjeshwar s").update({ age: "20" });
Upvotes: 1