如何使用ng2-dragula拖放到多个Angular2组件

时间:2016-03-14 06:56:46

标签: javascript drag-and-drop angular dragula

我有一个Angular2组件,使用ng2-dragula进行拖放,如下所示:

@Component({
  selector: 'my-comp',
  directives: [
    Dragula
  ],
  viewProviders: [
    DragulaService
  ],
  template: `
    <div class="my-div">
      <div *ngFor="#item of items" [dragula]='"card-bag"' [dragulaModel]='items'>
      ...
      </div>
    </div>
  `
})

我的问题:如果我创建多个“my-comp”组件,“card-bag”中的项目不能拖放这些组件,尽管它们具有相同的包名称。这些项目只能在其拥有的组件内拖放。

我们是否有任何跨组件拖放的配置,或者这是ng2-dragula限制?

感谢。

2 个答案:

答案 0 :(得分:10)

如果您没有使用[dragulaModel],那么只要您在顶部/根组件中设置viewProviders: [ DragulaService ]一次,嵌套组件之间的拖放效果就会很好。

请记住,不要在其他组件中设置viewProviders: [ DragulaService ],因为它会为每个组件创建新实例。

编辑:最近我使用ng2-dnd npm包实现了给定的场景。 它比ng2-dragula更好,并提供简单的物体传递和其他东西。 它可能会解决您的问题。

答案 1 :(得分:2)

我得到了一个树形结构拖放工作:

顶级组件

  • CSS ViewEncapsulation.None,包括任何css
  • Dragula指令
  • DragulaService ViewProvider
  • 在dragula服务上注册accepts过滤器,阻止项目被丢弃在内部

    accepts: (el: Element, target: Element, source: Element, sibling: Element): boolean => {
     return !el.contains(target); // elements can not be dropped within themselves
    },
    
  • 在dragula服务上注册moves过滤器,以便整个项目一起移动

    moves: (el: Element, container: Element, handle: Element): boolean => {
      // only move favorite items, not the icon element
      return el.tagName.toLowerCase() === 'mvp-navigation-item';
    },
    
  • Html模板看起来像这样

    <div class="nav--favorites__root" [class.is-dragging]="isDragging" [dragula]="'favorites'" [dragulaModel]="favoriteLinks">
      <navigation-item *ngFor="let link of links" [link]="link">
      </navigation-item>
    </div>
    

导航项目组件

  • Dragula指令
  • No DragulaService ViewProvider
  • Html模板看起来像这样

    <a href class="list-group-item" linkActive="active" [linkTo]="link?.url" (click)="followLink($event, link)">
      <span class="glyphicon glyphicon-{{link?.icon ? link?.icon : 'unchecked'}}"></span>
      <span class="nav__label">{{link?.label}}</span>
    </a>
    <div *ngIf="link?.children" class="list-group list-group-inverse nav--favorites__submenu" [class.is-expanded]="link?.isExpanded" [class.is-empty]="link?.children?.length === 0" [dragula]="'favorites'" [dragulaModel]="link?.children">
      <navigation-item *ngFor="let childLink of link?.children" [link]="childLink">
      </navigation-item>
      <!-- the nav favorites items must be the first elements in the dragula container or the model sync gets confused -->
      <a class="btn btn-link toggle" (click)="link.isExpanded = !link.isExpanded; $event.preventDefault();"><span class="glyphicon glyphicon-triangle-{{link?.isExpanded ? 'top' : 'bottom'}}"></span></a>
    </div>
    

你需要设置样式,以便在拖动项目时将.nav - favorites__子菜单显示为放置目标。