我有一些列表,可以添加/删除列表中的项目.

例如,当我在列表的中间(或底部)时,如果我将项目添加到列表中,滚动将移动到列表的顶部.(或者移动到某个索引,本例中为索引0).

告诉我如何在不改变示例 struct 的情况下从父组件滚动到子组件.

示例:https://stackblitz.com/edit/angular-ivy-ymbsj7

推荐答案

您的问题是,ViewChild在查询时不会进入更深的层次,因此无法在子元素模板中查询CdkVirtualScrollViewport.我可以用custom change detection function in your list component解决这个问题.

您应该将其从app.ts -> addItem()函数中删除:

 // want to move scroll to the top of the list
    this.viewPort.scrollToIndex(0, 'smooth');

而是在list component中创建自定义更改检测功能,但首先将CdkVirtualScrollViewport的viewChild移动到list component:

 export class ListComponent {
  @ViewChild(CdkVirtualScrollViewport) viewPort: CdkVirtualScrollViewport;
  @Input()
  data: Favorite[];

  @Output()
  removeData = new EventEmitter<Favorite>();

  remove($event) {
    this.removeData.emit($event);
  }

  ngOnChanges(changes: SimpleChanges) {
    if (
      changes.data &&
      changes.data.currentValue &&
      changes.data.previousValue &&
      changes.data.currentValue.length >changes.data.previousValue.length
    ) {
      this.viewPort.scrollToIndex(0, 'smooth');
    }
  }
}

这对我来说非常有效.每次添加项目时,它都会滚动到顶部.

修改了stackblitz链接:

https://stackblitz.com/edit/angular-ivy-k5pve6?file=src/app/list/list.component.ts

Another solution(and maybe better)可以将ListComponent作为模板引用传递给addItem()函数,然后使用Components viewPort property的滚动函数.

列表组件

...
export class ListComponent {
  @ViewChild(CdkVirtualScrollViewport)
  public viewPort: CdkVirtualScrollViewport;
...
}

AppComponentTemplate,模板引用传递ListComponent:


<p>Start editing to see some magic happen :)</p>
<input #inputText />
<button #addButton (click)="addItem(list)">Add New</button>
<list-container #list [data]="favoriteList" (removeData)="remove($event)">
</list-container>

应用组件->;addItem():


 addItem(listComp: ListComponent) {
    const newItem = {
      id: Number(this.input.nativeElement.value) + 1,
      title: `item ${Number(this.input.nativeElement.value) + 1}`,
    };

    this.favoriteList = [newItem, ...this.favoriteList];
    listComp.viewPort.scrollToIndex(0, 'smooth');
  }

第二种解决方案的StackBlitz:

https://stackblitz.com/edit/angular-ivy-ofhubv?file=src/app/app.component.html

Javascript相关问答推荐

我应该在redux reducer中调用其他reducer函数吗?

使用下表中所示的值初始化一个二维数组

通过嵌套模型对象进行Mongoose搜索

使用javascript将Plotly Expandable Sparkline转换为HighCharter Plot在bslib卡中

判断表格单元格中是否存在文本框

为什么promise对js中的错误有一个奇怪的优先级?

这个值总是返回未定义的-Reaction

为什么JPG图像不能在VITE中导入以进行react ?

在VS代码上一次设置多个变量格式

如何在FastAPI中为通过file:/URL加载的本地HTML文件启用CORS?

在表单集中保存更改时删除';禁用';

基于产品ID更新条带产品图像的JavaScript命中错误

是否可以将异步调用与useState(UnctionName)一起使用

如何在下一个js中更改每个标记APEXCHARTS图表的 colored颜色

递增/递减按钮React.js/Redux

Firefox的绝对定位没有达到预期效果

浮动标签效果移除时,所需的也被移除

单击子按钮时将活动切换类添加到父分区

JavaScript structuredClone在Chrome/Edge中获得了非法调用,但在NodeJS中没有

将数据对象代码中缺失的属性添加到单个对象不起作用