Search code examples
angularrxjsasync-pipe

Observable not updating the view


I'm trying to build a scheduler component for angular. However, when creating events it seems that the view is not being updated.

Angular schedular component

I've created a minimal StackBlitz that demonstrates the issue.

EDIT

I created a StackBlitz with the calendar component too. Note that the labels are being updated, but the divs on the calendar aren't.

export class AppComponent {
  constructor() {
    this.calendarEvents$ = new BehaviorSubject<CalendarEvent[]>([]);

    this.calendarEventParts$ = this.calendarEvents$
      .pipe(map((events) => {
        // Split event over the days it goes...
        return events.map(ev => <CalendarEventPart>{
          calendarEvent: ev
        });
      }));
  }

  calendarEvents$: BehaviorSubject<CalendarEvent[]>;
  calendarEventParts$: Observable<CalendarEventPart[]>;

  onAddEvent() {
    this.christmas = {...};
    this.calendarEvents$.pipe(take(1))
      .pipe(map((events) => events.push(this.christmas)))
      .subscribe(() => {});
  }

  onChangeChristmasStart() {
    this.christmas.start = new Date(2022, 11, 24);
  }
}

The BehaviorSubject updates the view as expected, but after using the map operator the view isn't being updated. I've already done this.calendarEvents$.next(data) but this does not solve the core issue, and prevents from property changes being detected.

Edit

I've updated the code in order to look for changes manually and force trigger the change detector explicitly. However even when calling changeDetectorRef.detectChanges() only when necessary, the view is still not updated.


Solution

  • You need to update your calendarEvents$ behaviour subject.

    onAddEvent() {
       this.christmas = {...};
       this.calendarEvents$.next([...this.calendarEvents$.value, this.christmas]);
    }