angular - 无法读取未定义的属性 - cdkDropListData 拖放 Angular Material

标签 angular angular-material drag-and-drop

我正在使用新的 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/

相关文章:

javascript - 未捕获( promise ): TypeError: Cannot read property 'component' of null

php - JSON.解析 : unexpected end of data at line 1 column 1 of the JSON data( Angular2 backend php server SQL)

javascript - 如何在 Angular 2中的选择标签中显示颜色框?

drag-and-drop - 如何在旧版本的Processing中选择并拖动椭圆?

java - Vaadin JPAContainer 和树拖放

javascript - Typescript Angular2 - 提示缺少类型

javascript - ng2-smart-table如何更改自定义按钮在点击时的显示和隐藏

javascript - 如何用 MatdialogRef 显示对话框?

css - Angular Material : How to set each mat-horizontal-stepper stepper icon with different background color in TS

c# - IDataObject 拖放问题,从 __ComObject 转换