簡體   English   中英

無法讀取未定義的屬性 - cdkDropListData 拖放 Angular Material

[英]Cannot read property of undefined - cdkDropListData drag-drop Angular Material

我正在使用新的 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提到的,原因是:

問題是 _DragRef.initialContainer == 未定義。 這是因為 _DragRef.initializeDragSequence() 的調用早於 _DragRef.withDropContainer()。 _initializeDragSequence() 基於 _dropContainer 初始化 _initialContainer,_dropContainer 由 _withDropContainer() 初始化,但因為 _initializeDragSequence() 比 _withDropContainer() 調用早,所以 _initialContainer 設置為 undefined。 更多信息: https : //github.com/angular/components/blob/master/src/cdk/drag-drop/drag-ref.ts

一個丑陋但可行的解決方法是在 AfterViewChecked 上觸發更改檢測,如下所示(由 lukaszgodula @ 上面的同一個 github):

ngAfterViewChecked() {
   this.cdRef.detectChanges();
}

當然還有將 ChangeDetectorRef 注入到組件中:

constructor(
   private cdRef: ChangeDetectorRef
}

確保先初始化user1數組

user: yourType = {};

this.userService.getUserById('some-user-id').subscribe(user => {
  this.user1 = user;
  console.log(user1.route.routePoints); // I see the array in log
}); 

我收到這個錯誤是因為我的 cdkDropListData 元素不是 cdkdrag 元素的直接父元素,中間有 tab 元素導致了問題。 它的 ng 版本 7.x

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM