Jonasty
Jonasty

Reputation: 105

AngularFire2 update list item triggers list change

My update call to firebase is working but it seems to refresh the list on which I loop, causing my input to lose focus.

Any way I can fire the update without the original list to refresh or just to catch this? I will be adding more fields per object to change.

component.ts

  quiz_ref: AngularFireList<any>;
  quiz_items : Observable<any[]>;


  constructor(afs: AngularFireDatabase){
    this.quiz_ref = afs.list('quiz/questions', ref => ref.orderByChild('id'));
    this.quiz_items = this.quiz_ref.snapshotChanges().map(changes => {
      return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
   });
  }

  updateItem(key: string, item) {
    this.quiz_ref.update(key,item);
  }

component.html

<div class="row">

  <div class="col-md-12" *ngFor="let item of quiz_items| async ">
    <div class="col-md-10 offset-md-1">
      <mat-expansion-panel [expanded]='true' >

        <mat-expansion-panel-header>
          <mat-panel-title>
           {{item.id}}
          </mat-panel-title>
        </mat-expansion-panel-header>
        <div class="row">
          <div class="col-md-12">
            <mat-form-field>
              <input matInput type="text" placeholder="Vraag NL" 
                    [(ngModel)]="item.question_nl" 
                    (ngModelChange)="updateItem(item.key,item)" >
            </mat-form-field>
          </div>
        </div>
      </mat-expansion-panel>
    </div>
  </div> 
</div>

Upvotes: 1

Views: 221

Answers (1)

Eric Larson
Eric Larson

Reputation: 519

Look into using 'track by' in *ngFor.

HTML

<div class="col-md-12" *ngFor="let item of quiz_items| async; trackBy: trackFn">

</div>

TS

public trackFn(index, item) {
    return item ? item.id : undefined;
}

Upvotes: 1

Related Questions