Skip to content Skip to sidebar Skip to footer

Angular: Cdkvirtualfor Not Rendering New Items

I'm building a vertically scrolling calendar. I'm getting the initial days to load, but when new days are added to the list, they aren't being rendered.

Solution 1:

The *cdkVirtualFor would only be updated if you update it immutably i.e. you cannot update the array after it is initialized. We use the spread operator to get what you are looking for.

Check this very simple stackblitz... here i have used 2 methods which you can try and see:

  • addCountryOld method mutates the array by pushing an object to our array and hence the rendered view is not updated.
  • addCountryNew method uses immutability through the spread operator which results in the rendered view getting updated.

This is the code for addCountryNew:

addCountryNew(){
    let  newObj = {'name':'stack overflow country', "code":'SO'};
    this.myList = [...this.myList, newObj];
  }

Solution 2:

I figured this out.

Originally, I was adding new days by grabbing the current value like this

let items = this.items$.value;
items.push(newItem);
this.items$.next(items)

Apparently, this is actually a mutation of the value of the BehaviorSubject's value, therefore not creating a new array to return and not triggering change detection.

I changed it to

let items = [...this.items$.value];
items.push(newItem);
this.items$.next(items)

and all is good.

So, although the answers here are correct in that I was mutating the original array, the information I needed was calling next() with a mutated version BehaviorSubject's current value does not emit a new array. An emit event does not guarantee immutability.

Solution 3:

Instead of

this.days = days;

do

this.days = [...days];

Works. https://stackblitz.com/edit/material-infinite-calendar-amcapx?file=src/app/calendar/calendar.component.ts

(But does it mean that BehaviorSubject keeps reusing and mutating the same object? Weird!)

Solution 4:

It can be done like this:

You can initialise another variable as observale of your behaviorsubject "days$".

in calendar-days.service.ts

publicdays$: BehaviorSubject<Date[]>;
  publicdayObs$: Observable<Date[]>

  constructor() {
    this.days$ = newBehaviorSubject<Date[]>(this._initialDays);
    this.dayObs$ = this.days$.asObservable();
  }

And then subscribe that observable in calender.component.ts inside ngOnInit like this:

this._daysService.dayObs$.subscribe(days => {
  this.days = days;
})

Post a Comment for "Angular: Cdkvirtualfor Not Rendering New Items"