You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Material拖拽:滚动条移至内部div后自动滚动失效

解决Angular Material拖拽自动滚动失效问题(滚动条移至内部div场景)

当把滚动容器从默认外层元素改为内部div后,Angular Material CDK的拖拽自动滚动功能会失效——原因是CDK默认不会自动识别自定义的内部滚动容器,需要手动指定绑定。以下是适配动态条目场景的解决方案:

步骤1:给内部滚动容器添加模板引用

在模板中给内部滚动div加上模板变量,方便组件类获取元素引用:

<div #scrollContainer class="inner-scroll">
  <div cdkDropList class="drag-list">
    <div cdkDrag *ngFor="let item of items" class="drag-item">
      {{ item }}
    </div>
  </div>
</div>

<!-- 动态添加条目的按钮示例 -->
<button (click)="addItem()">添加新条目</button>

步骤2:绑定滚动容器到拖拽列表

在组件类中通过ViewChild获取滚动容器和拖拽列表的引用,然后将滚动容器绑定到拖拽列表的scrollContainer属性:

import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { CdkDropList } from '@angular/cdk/drag-drop';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
  @ViewChild('scrollContainer') private scrollContainer!: ElementRef<HTMLElement>;
  @ViewChild(CdkDropList) private dropList!: CdkDropList;

  items = Array.from({ length: 30 }, (_, i) => `条目 ${i + 1}`);

  ngAfterViewInit(): void {
    // 将内部滚动容器绑定到拖拽列表
    this.dropList.scrollContainer = this.scrollContainer.nativeElement;
  }

  // 动态添加条目方法
  addItem(): void {
    this.items.push(`条目 ${this.items.length + 1}`);
  }
}

步骤3:配置滚动容器样式(无需固定高度)

通过CSS确保内部容器在内容超出时自动出现滚动条,同时支持动态内容扩展:

.inner-scroll {
  overflow-y: auto;
  min-height: 200px; /* 设置最小高度保证初始可滚动区域,可按需调整 */
  /* 若使用flex布局,可替换为flex: 1让容器填充父级可用空间 */
}

.drag-list {
  padding: 0;
  margin: 8px;
}

.drag-item {
  padding: 12px;
  margin-bottom: 8px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

关键说明

  • 此方案无需设置固定高度或最大高度,动态添加条目后容器会自动扩展,超出最小高度时触发滚动。
  • scrollContainer属性会让CDK拖拽系统监听指定容器的滚动事件,拖拽时靠近容器边缘就会触发自动滚动。

内容的提问来源于stack exchange,提问作者John Jepeto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 09:25:03