2016-12-05 83 views
0

我有一個水果列表和籃子列表。我需要挑一個水果並放在一個籃子裏。我使用this tutorial來實現拖放概念。但我不能把水果放在一個籃子裏。如果我把一個水果拖放到籃子裏,所有的籃子都會得到那個水果。拖放嵌套列表

我知道問題在於這一行,我不應該爲每個籃子使用同名fruit。我需要動態分配它。或者有沒有更好的方式來做到這一點。任何意見將是有益的。謝謝。

<li *ngFor="let fruit of fruitsInBasket; let i = index" class="list-group-item" dnd-sortable [sortableIndex]="i">{{fruit.name}}</li> 

這裏是我的代碼:

app.component.ts

import { Component } from '@angular/core'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 
    listBaskets: Array<Basket> = [ 
    { 
     id: 1, name: 'Basket 1' 
    }, { 
     id: 2, name: 'Basket 2' 
    }, { 
     id: 3, name: 'Basket 3' 
    }, { 
     id: 4, name: 'Basket 4' 
    },]; 
    listFruits: Array<Fruit> = [ 
    { 
     id: 1, name: 'Apple' 
    }, { 
     id: 2, name: 'Orange' 
    }, { 
     id: 3, name: 'Mango' 
    }, { 
     id: 4, name: 'Strawberry' 
    },]; 
    fruitsInBasket: Array<Fruit> = []; 
    constructor() { } 

} 

export interface Basket { 
    id: number; 
    name: string; 
} 
export interface Fruit { 
    id: number; 
    name: string; 
} 

app.component.html

<div class="row"> 
    <div class="col-sm-3"> 
    <div class="panel panel-warning"> 
     <div class="panel-heading"> 
     Available Baskets 
     </div> 
     <div class="panel-body"> 
     <ul class="list-group"> 
      <div class="panel panel-warning" *ngFor="let basket of listBaskets; let boxer=index"> 
      <div class="panel-heading"> 
       {{basket.name}} 
      </div> 
      <div class="panel-body" dnd-sortable-container [dropZones]="['boxers-zone']" [sortableData]="fruitsInBasket"> 
       <ul class="list-group"> 
       <li *ngFor="let fruit of fruitsInBasket; let i = index" class="list-group-item" dnd-sortable [sortableIndex]="i">{{fruit.name}}</li> 
       </ul> 
      </div> 
      </div> 
     </ul> 
     </div> 
    </div> 
    </div> 
    <div class="col-sm-3"> 
    <div class="panel panel-success"> 
     <div class="panel-heading"> 
     Fruits 
     </div> 
     <div class="panel-body" dnd-sortable-container [dropZones]="['boxers-zone']" [sortableData]="listFruits"> 
     <ul class="list-group"> 
      <li *ngFor="let fruit of listFruits; let i = index" class="list-group-item" dnd-sortable [sortableIndex]="i">{{fruit.name}}</li> 
     </ul> 
     </div> 
    </div> 
    </div> 
</div> 

輸出:

enter image description here

回答

0

爲什麼你看到了同樣的水果中的所有籃子的原因是因爲您只使用一個fruitsInBasket陣列來存儲水果所有的人。

完成此操作的最佳方法是對每個籃子使用單獨的數組,並將丟棄的水果推到可丟棄的onDropSuccess上。查看文檔here

0

此行是你的問題

// app.component.ts 
... 
fruitsInBasket: Array<Fruit> = []; 

你存儲所有的格子,相同的數據,所以當你在其中的一個掉落的水果,就在所有的人都放棄它。

考慮改變fruitsInBasket類型

// app.component.ts 
... 
fruitsInBasket: { [basket: number]: Array<Fruit> }; 

和重寫組件,牢記你保持每個籃子單獨的數據存儲。