I'm working on my master degree and i have a bug. I'm pretty sure it's something easy but i can't figure it out. I'm working with Angular, Firestore and RxJs for it. The big problem is that the ui is not updated. On init of the page, the array with my infos is empty and in a short time, it is filled with a new comment exactly as expected.
So, i have a parent component, university.html
:
<div *ngIf="reviewsData.length > 0">
<app-editable-comments
*ngFor="let review of reviewsData"
[review]="review">
</app-editable-comments>
And the child component app-editable-comments.html
which only render the infos to the screen.
I'm getting the data in university.ts
using ngOnInit
:
this.firebaseService.getReviewsData().subscribe(data => {
this.reviewsData = [];
data.forEach(review => {
const reviewDetails = new ReviewData(review);
if (reviewDetails.universityId === this.universityId) {
this.reviewsData.push(reviewDetails);
}
});
});
Until now everything it's fine. But there is another function which is called in ngOnInit
as well:
if (this.user.id && this.universityId) {
this.showAddNewComment();
this.changeDetectorRef.markForCheck(); // i tried it and is not working
}
The showAddNewComment()
method it's only verifying if the array with the reviews already have a review from logged user or it needs to add a new one to initialize a new comment:
showAddNewComment() {
if (this.reviewsData.filter((item: ReviewData) => item.userId === this.user.id).length === 0) {
const newCommentForPresentLoggedInUser = {
universityId: this.universityId,
userId: this.user.id,
date: new Date()
};
this.reviewsData.push(new ReviewData(newCommentForPresentLoggedInUser));
}
}
Any ideas? I'm trying to fix this from a long time...
while working with Angular and change detection it's always better to not edit data implace in showAddNewComment u are doing it
i think u should do it like this.
showAddNewComment() {
let newArray = [...this.reviewsData]
if (this.reviewsData.filter((item: ReviewData) => item.userId === this.user.id).length === 0) {
const newCommentForPresentLoggedInUser = {
universityId: this.universityId,
userId: this.user.id,
date: new Date()
};
newArray.push(new ReviewData(newCommentForPresentLoggedInUser));
}
this.reviewsData = newArray;
}