Angular: cdkVirtual 不渲染新项目 [英] Angular: cdkVirtualFor not rendering new items

查看:21
本文介绍了Angular: cdkVirtual 不渲染新项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个垂直滚动的日历.我正在加载最初的日子,但是当新的日子添加到列表中时,它们不会被呈现.

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.

<cdk-virtual-scroll-viewport
  class="demo-viewport"
  [itemSize]="100"
  (onContentScrolled)="handleScrollChange($event)"
>
  <calendar-day
    *cdkVirtualFor="let day of days; trackBy: trackByFn"
    [day]="day"
  ></calendar-day>
</cdk-virtual-scroll-viewport>
<button (click)="goToToday()">go</button>

我有一个带有 BehaviorSubject 更新日期的服务.我知道天数列表正在更新,但似乎没有检测到更改.

I have a service with a BehaviorSubject updating the days. I know the list of days is being updated, but the change doesn't seem to be detected.

  ngOnInit() {
    this._daysService.days$.subscribe(days => {
      this.days = days;
    })
    this.watchScroll();
    this.handleScrollingUp();
    this.handleScrollingDown();
  }

有关更多信息,StackBlitz 存储库是公开的 https://stackblitz.com/edit/material-无限日历

For more info, the StackBlitz repo is public https://stackblitz.com/edit/material-infinite-calendar

推荐答案

我想通了.

最初,我通过像这样抓取当前值来添加新天

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)

显然,这实际上是对 BehaviorSubject 的值的改变,因此不会创建新的数组返回,也不会触发更改检测.

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.

我改成

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

一切都很好.

所以,虽然这里的答案是正确的,因为我正在改变原始数组,但我需要的信息是调用带有变异版本的 BehaviorSubjectnext()> 的当前值不会发出 new 数组.emit 事件并不能保证不变性.

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.

这篇关于Angular: cdkVirtual 不渲染新项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆