Angular2/Angularfire2 - How do/can I get the key values of items in FirebaseListObservable?

时间:2016-10-20 19:43:57

标签: angular angularfire2

I am using angular 2.0.0-rc.3 & angularfire 2.0.0-beta.2

I have the following structure in my firebase DB

- trivia
     - questionData
       - 20161003
         - answer:1
         - options
            - 1: "In a car trunk"
            - 2: "Under dead bodies"
            - 3: "Up a tree"
            - 4: "In a ditch"
         - questionText: "Where do Daryl and Beth hide..."
       - 20161002...
       - 20161001...

I have the following code:

export class UserDataComponent {
    questionData: FirebaseListObservable<any[]>;

    constructor(public af: AngularFire) {
        this.questionData = af.database.list("/questionData");
    }

}

And this HTML

<ul>
<li *ngFor="let question of questionData | async">
    <div class="question-container">
        <p>{{ question.questionText }}</p>
        <ul>
            <li *ngFor="let answer of question.options">
                <input type="radio" name="{{answer-key-here}}" value="{{answer-key-here}}" id="{{answer-key-here}}" [(ngModel)]="userAnswer"/>
                <label htmlFor="{{answer-key-here}}"> {{ answer }} </label>
            </li>                
        </ul>
        <button (click)="submitAnswer()">Submit</button>
    </div>
</li>

OK, so with that in mind. Looking at the expanded question entry above, I want to list out the answers, but would like to get the key values (1, 2, 3, 4) and have them write out to the name, id, htmlFor attributes. My anticipation would be that it would output HTML like this:

<ul>
<li *ngFor="let question of questionData | async">
    <div class="question-container">
        <p>Where do Daryl and Beth hide...</p>
        <ul>
            <li *ngFor="let answer of question.options">
                <input type="radio" name="1" value="1" id="1" [(ngModel)]="userAnswer"/>
                <label htmlFor="1"> In a car trunk </label>
            </li>                
        </ul>
        <button (click)="submitAnswer()">Submit</button>
    </div>
</li>

I haven't been able to figure out how to accomplish this. Can anyone point me in the right direction, and help me understand what I am missing?

1 个答案:

答案 0 :(得分:1)

您的question.options对象将是字典。如果要以这种方式使用它,可以使用管道将其转换为数组。还有一些方法可以保留密钥:have a look at this SO-question