如何将Angular CDK的cdkDropListDropped事件绑定到宿主组件?
解决Angular宿主组件绑定cdkDropListDropped事件的问题
你遇到的问题根源在于:仅通过@HostBinding('attr.cdkDropList')给宿主元素添加属性,并没有真正让Angular CDK的cdkDropList指令作用在宿主组件上。cdkDropList是一个Angular指令,需要被Angular实例化才能生效,单纯的HTML属性无法触发指令的初始化,因此事件处理程序不会被调用。
正确的实现方式
直接在组件装饰器的host配置中声明cdkDropList指令和对应的事件绑定,这样Angular会正确识别并初始化cdkDropList指令,同时绑定拖拽完成事件:
import { ChangeDetectionStrategy, Component, } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CdkDropList, CdkDrag, CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop'; @Component({ selector: 'my-list', standalone: true, imports: [CommonModule, CdkDropList, CdkDrag], templateUrl: './my-list.component.html', styleUrls: ['./my-list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, // 在这里配置宿主的指令和事件绑定 host: { '[cdkDropList]': 'true', '(cdkDropListDropped)': 'onDrop($event)' } }) export class MyListComponent { protected list: string[] = ['Item 1', 'Item 2', 'Item 3']; onDrop(event: CdkDragDrop<string[]>): void { console.log(event); moveItemInArray(this.list, event.previousIndex, event.currentIndex); } }
模板配合修改
确保你的组件模板中,列表项都添加了cdkDrag指令,这样它们才能被拖拽:
<!-- my-list.component.html --> <div *ngFor="let item of list" cdkDrag> {{ item }} </div>
为什么原来的方法无效?
@HostBinding('attr.cdkDropList')只是在宿主元素的HTML上添加了cdkDropList属性,但Angular并不会因为这个属性自动实例化cdkDropList指令。只有通过组件装饰器的host配置、或者直接在模板元素上添加cdkDropList指令,Angular才会识别并创建指令实例,进而触发相关的拖拽事件。
内容的提问来源于stack exchange,提问作者Paul McConico
相关产品推荐
相关产品推荐

