I am just getting started with Angular 2 after working with AngularJS for the last couple of years.
I have a Component which displays some info about the user and depending on which variable is declared, The markup will adjust according the value of showStuff
variable. stuff2
is the default. stuff1
should display a repeated list of data. When the user clicks showStuffOne()
, the variable does change to the correct value however the data that is subscribed in the function is not being updated to the view.
I'm a bit stumped on the correct "angular2" way to update a view when the model changes in this particular instance. I've seen multiple posts about DetectionChange, ngZone and behaviorSubject, but not really sure what direction would solve this. Consider the following:
user-page.html
<ion-row>
<ion-col>
<button ion-button block (click)="showStuffOne()"> Stuff1 </button>
</ion-col>
<ion-col>
<button ion-button block> Store </button>
</ion-col>
<ion-col>
<button ion-button block (click)="showStuffTwo()"> Stuff2 </button>
</ion-col>
</ion-row>
<ion-list *ngIf="showStuff == 'stuff1'" ngFor="let event of eventList" >
<h3>{{event.title}}</h3>
<span>{{event.location}}</span>
</ion-list>
<ion-list *ngIf="showStuff == 'stuff2'">stuff2</ion-list>
user-page.ts:
import { Component, NgZone, OnInit, ChangeDetectorRef } from '@angular/core';
import { NavController, NavParams, ModalController } from 'ionic-angular';
import { AngularFireDatabase, FirebaseObjectObservable, FirebaseListObservable} from 'angularfire2/database';
import * as firebase from 'firebase/app';
@Component({
templateUrl: 'user-page.html',
selector: 'user-page'
})
export class UserPage {
userId: string;
eventList: string[];
showStuff: string;
constructor(private cd: ChangeDetectorRef, private zone: NgZone, public navCtrl: NavController, public navParams: NavParams, private afDB: AngularFireDatabase, public modalCtrl: ModalController) {
console.log(this.navParams.get('username'))
var getUsr = afDB.list('https://myendpoint.com/users', {
query: {
orderByChild: 'uname',
equalTo: this.navParams.get('username')
}
}).subscribe(data => {
console.log(data)
this.userId = data[0].uid;
})
}
ngOnInit() {
this.showStuff = 'stuff2';
}
showStuffOne() {
console.log("stuff1")
this.userEvents(this.userId);
}
showStuffTwo() {
console.log("stuff2")
this.showStuff = 'stuff2';
}
openEvent = function(key) {
console.log(key)
let eventObj = {
eventKey: key
}
let eventModal = this.modalCtrl.create(EventModal, eventObj);
eventModal.present()
};
userEvents(userid: string) {
var getUsrEvnts = this.afDB.list("http://myendpoint.com/event", {
query: {
orderByChild: "created_by",
equalTo: userid
}
}).subscribe(data => {
this.showStuff = 'stuff1'; // this correctly updates the variable, changing the view
this.eventList = data; // data not updating, returning undefined, however the data logs here
console.log(this.eventList)
})
}
}
EDIT: answer can be found at this posting