如何在TypeScript中动态设置cdkDrag的边界?
在TypeScript中设置cdkDrag的拖拽边界
可以通过cdkDrag实例的withBoundaryElement方法指定拖拽边界,具体实现如下:
- 确保传入的
container是有效的DOM元素或ElementRef实例 - 在
ngAfterViewInit中调用withBoundaryElement方法绑定边界元素
修改后的代码:
@Input() public container: ElementRef<HTMLElement> | HTMLElement; constructor(public el: ElementRef, private dragDropService: DragDrop) { } ngAfterViewInit(): void { const cdkDrag = this.dragDropService.createDrag(this.el); // 将拖拽边界设置为传入的container元素 if (this.container) { const boundaryElement = this.container instanceof ElementRef ? this.container.nativeElement : this.container; cdkDrag.withBoundaryElement(boundaryElement); } }
补充说明
withBoundaryElement仅接受HTMLElement类型参数,若container是ElementRef,需先取出其nativeElement属性- 设置后,拖拽元素会被限制在指定边界元素内部移动,超出边界时会自动"回弹"到边界范围内
内容的提问来源于stack exchange,提问作者Lei Chi
相关产品推荐
相关产品推荐

