使用Angular2的自定义组件时,JQueryUI Sortable无法正常工作

tyr*_*ion 4 jquery-ui jquery-ui-sortable angular

我的目标是允许用户对命令列表进行排序.我正在使用Angular2/Typescript开发我的应用程序.

所以我四处寻找基于angular2的库,这些库可以提供类似于JQueryUI Sortable的可排序功能,但是找不到多少.

我遇到了这个 SO帖子,它演示了如何将JQuery与angular2集成.使用此帖子的其中一个解决方案中提供的plunk,我可以使用angular2开发一个可排序的行为.看到这个插件.这是按预期工作的.

@Component({
  selector: 'my-app',
  directives: [SMSortable],
  providers: [],
  template: `
    <div>
      <p>This is a list that can be sorted </p>
      <div sm-sortable>
        <p>Item 1</p>
        <p>Item 2</p>
        <p>Item 3</p>
      </div>
    </div>
  `
})
export class App {
  constructor() {
    this.name = 'Angular2'
  }
}
Run Code Online (Sandbox Code Playgroud)

我们的想法是定义一个指令,该指令将使用JQueryUI sortable()API将可排序行为应用于本机元素.然后在组件的模板中使用该指令.

@Directive({
  selector: "[sm-sortable]"
})
export class SMSortable{

    constructor(el: ElementRef) {
        jQuery(el.nativeElement).sortable( {
              start: function(event, ui) {
                  console.log("Old position: " + ui.item.index());
              },
              stop: function(event, ui) {
                  console.log("New position: " + ui.item.index());
              }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

当组件的模板具有所有本机元素时,这很有效.但是,如果我的模板具有自定义angular2组件,则此操作将停止.

看到这个不工作的插件.

@Component ({
  selector: 'sm-cmd',
  template: '<ng-content></ng-content>'
})
export class SMCommand {

}

@Component({
  selector: 'my-app',
  directives: [SMSortable, SMCommand],
  providers: [],
  template: `
    <div>
      <p>This is a list that can be sorted </p>
      <div sm-sortable>
        <sm-cmd><p>Item 1</p></sm-cmd>
        <sm-cmd><p>Item 2</p></sm-cmd>
        <sm-cmd><p>Item 3</p></sm-cmd>
      </div>
    </div>
  `
})
export class App {

}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我可以拖动项目,但不能删除它.移动的项目将恢复为原始位置.我添加了console.log以在排序期间查看启动和停止事件中的项目索引.价值保持不变.

我无法进一步调试此问题.有人可以就此提供一些意见吗?

dfs*_*fsq 5

问题实际上非常简单:因为您使用自定义元素sm-cmd浏览器不知道要使用哪种渲染模型(块或内联).默认情况下,它应用内联一,这会导致元素维度方面的冲突,因为p内部有块级内联sm-cmd.因此浏览器无法正确计算块尺寸.

所以解决方案是这个简单的CSS规则:

sm-cmd {display: block;}
Run Code Online (Sandbox Code Playgroud)

还要确保在ngAfterViewInit钩子中初始化jQuery插件:

@Directive({
  selector: "[sm-sortable]"
})
export class SMSortable{

  constructor(private el: ElementRef) {}

  ngAfterViewInit() {
      jQuery(this.el.nativeElement).sortable( {
            start: function(event, ui) {
                console.log("Old position: " + ui.item.index());
            },
            stop: function(event, ui) {
                console.log("New position: " + ui.item.index());
            }
      });
  }
}
Run Code Online (Sandbox Code Playgroud)

演示: http ://plnkr.co/edit/QEd9wozXSZlqT07qr51h?p =preview