jQuery   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了jquery-ui – 在使用Angular2的自定义组件时,JQueryUI Sortable无法正常工作大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我的目标是允许用户对命令列表进行排序.我正在使用Angular2 / Typescript开发我的应用程序.

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

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

@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'
  }
}

我们的想法是定义一个指令,该指令将使用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());
              }
        });
    }
}

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

not-working plunk.

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

}

@Component({
  SELEctor: 'my-app',directives: [SMSortable,SMCommand],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 {

}

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

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

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

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

sm-cmd {display: block;}

还要确保在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());
            },ui) {
                console.log("New position: " + ui.item.index());
            }
      });
  }
}

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

大佬总结

以上是大佬教程为你收集整理的jquery-ui – 在使用Angular2的自定义组件时,JQueryUI Sortable无法正常工作全部内容,希望文章能够帮你解决jquery-ui – 在使用Angular2的自定义组件时,JQueryUI Sortable无法正常工作所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。