4

I have the following snippet

This is my main.html

<h2 class="txtcenter po-2text" style="padding-top:30px">
    {{title}}
</h2>

This is my main.ts:

title: string;

ngOnInit() {
    var self = this;
    var ref = firebase.database().ref('schools/' + this.currentUserId());
    ref.orderByChild('title').on('value', function(dataSnapshot) {
        console.log("Title is: " + dataSnapshot.val().title);
        self.title = dataSnapshot.val().title;
    });
}

Even though the callback gets fired with some valid data, the title doesn't update automatically. What am I missing?

Any help is appreciated!

4
  • Can you please create a working sample of this? You can try creating a StackBlitz if possible. Also try changing the syntax to fat-arrow function syntax and check if that helps. Try changing your ngOnInit like this: ngOnInit() { const ref = firebase.database().ref('schools/' + this.currentUserId()); ref.orderByChild('title').on('value', dataSnapshot => this.title = dataSnapshot.val().title); } Commented Oct 5, 2018 at 9:15
  • @LuigiCapgrosso So console.log works fine? Commented Oct 5, 2018 at 9:18
  • You may want to check github.com/angular/angularfire2 Commented Oct 5, 2018 at 9:21
  • Yes, console.log works fine Commented Oct 5, 2018 at 9:23

1 Answer 1

7

Angular change detection works based on browser events, since this is a fire base event callback this wont trigger the change detection. So try the following

Import NgZone:

import { Component, NgZone } from '@angular/core';

Add it to your class constructor

constructor(public zone: NgZone, ...args){}

Run code with zone.run:

ref.orderByChild('title').on('value', (dataSnapshot) => {
        console.log("Title is: " + dataSnapshot.val().title);
        this.zone.run(() => this.title = dataSnapshot.val().title;)
});
Sign up to request clarification or add additional context in comments.

1 Comment

@LuigiCapogrosso :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.