Prajeet Shrestha
Prajeet Shrestha

Reputation: 8108

How to create child with autoid in Firebase with Angularfire2?

af.database.object('item').set({ name: newName });

I can save value in a known node with this method in AngularFire2.

I want to know how to save in a unique node each time like this.

In Swift there is something like this:

node.childByAutoId().setValue([key: value]);

Upvotes: 0

Views: 2239

Answers (2)

Prajeet Shrestha
Prajeet Shrestha

Reputation: 8108

Turns out there is no one liner for this. In AngularFire2 the push method is only available on FirebaseListObservables but not FirebaseObjectObservable. So here is a small component for demonstrating this:

import { Component } from '@angular/core';
import {AngularFire, FirebaseListObservable } from 'angularfire2';

@Component({
    selector: 'auto',
    template: `
    <ul>
        <li class="text" *ngFor="let p of person | async">
            {{p.name}}
         </li>
    </ul>
    <input type="text" #newname placeholder="Name" />
    <br />
    <button (click)="save(newname.value)">Set Name</button>
    `
})

export class AutoComponent {
    person: FirebaseListObservable<any>;
    constructor(private af: AngularFire) {
        this.person = af.database.list('person')
    }
    save(newName: string) {
        this.person.push({ "name": newName });
    }
}

Upvotes: 1

Mathew Berg
Mathew Berg

Reputation: 28750

Do you mean to use .push?

node.child('items').push({ key: value })

Or do you mean you want to save a node with that key? If so then do this:

node.child('items').child(key).set(value);

Upvotes: 0

Related Questions