我正在使用新的 Angular 7 Material CDK 拖放功能将项目从一个列表移动到另一个列表,并且在移动这些项目时视觉上一切都在晃动,但是当通过列表更改项目时,我收到一条错误消息,说无法获取属性(列表数组)来自未定义,即使我使用的是“item?.array”的东西
在构造函数中:
this.userService.getUserById('some-user-id').subscribe(user => {
this.user1 = user;
console.log(user1.route.routePoints); // I see the array in log
});
this.userService.getUserById('some-other-user-id').subscribe(user => {
this.user2 = user;
console.log(user2.route.routePoints); // I see the array in log
});
在这里,将项目从列表拖到另一个列表时,出现错误“无法读取未定义的属性‘routePoints’”
<div cdkDropList #routeA="cdkDropList" cdkDropListOrientation="horizontal"
[cdkDropListData]="user1?.route?.routePoints"
class="list" (cdkDropListDropped)="drop($event, false, user1)"
[cdkDropListConnectedTo]="[queue, routeB]">
这是拖动代码:
drop(event: CdkDragDrop<RoutePoint[]>, fromQueue: boolean = false, user: User) {
if (event.previousContainer === event.container) {
moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
} else {
transferArrayItem(event.previousContainer.data, event.container.data, event.previousIndex, event.currentIndex);
}
this.userService.updateUser(user);
}
最佳答案
作为 marcinolawski @ https://github.com/angular/components/issues/15948提到,原因是:
The problem is that _DragRef.initialContainer == undefined. This is because _DragRef.initializeDragSequence() is called earlier than _DragRef.withDropContainer(). _initializeDragSequence() initializes the _initialContainer based on _dropContainer, _dropContainer is initialized by _withDropContainer() but because _initializeDragSequence() is called earlier than _withDropContainer() _initialContainer is set to undefined. More info: https://github.com/angular/components/blob/master/src/cdk/drag-drop/drag-ref.ts
一个丑陋但可行的解决方法是在 AfterViewChecked 上触发更改检测,如下所示(由 lukaszgodula @ 上面的同一个 github):
ngAfterViewChecked() {
this.cdRef.detectChanges();
}
当然还有将 ChangeDetectorRef 注入(inject)到组件中:constructor(
private cdRef: ChangeDetectorRef
}
关于angular - 无法读取未定义的属性 - cdkDropListData 拖放 Angular Material,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53878892/