【问题标题】:Elegant way to apply jquery plugin in Angular2在 Angular2 中应用 jquery 插件的优雅方式
【发布时间】:2017-11-21 11:25:21
【问题描述】:

我在 ngOnInit 块中从 web 服务获取数据,然后我需要应用 jquery 数据表插件(我在 ngAfterViewInit 和 ngAfterContentInit 中都执行了此操作)。问题是 jquery 数据表插件在 ngOnInit 块中获取的组件表中看不到数据。我可以实现这一点的唯一方法是 setTimeout 或 setInterval(如果创建了插件实例,它将停止执行)。

还有其他方法可以执行我尝试的任务吗?

export class DataTable implements OnInit, AfterViewInit, AfterContentInit, AfterContentChecked {

  public data = null;
  public table = null;

  constructor(public translate: TranslateService, public ngZone: NgZone) {
  }

  ngOnInit(): void {
    this.translate.getData().subscribe((records) => {
      this.data = records;
    });
  }

  ngAfterViewInit(): void {
   this.dataTableDynamicUpdater();
  }

  ngAfterContentInit() : void {

  }

  ngAfterContentChecked() {

  }


  dataTableDynamicUpdater() {
    let self = this;
    let interval = setInterval(() => {
      if(self.data) {
        self.instantiateDataTable();
        clearInterval(interval);
      }
    }, 200);
  }

  instantiateDataTable() {

    let _FILTER_PLACEHOLDER_ = this.translate.instant('APP_DATATABLE_PLACEHOLDER_TYPE_TO_FILTER');
    let _FILTER_LABEL_ = this.translate.instant('APP_DATATABLE_LABEL_FILTER');
    let _SHOW_LABEL_ = this.translate.instant('APP_DATATABLE_LABEL_SHOW');

    $.extend($.fn.dataTable.defaults, {
      autoWidth: false,
      dom: '<"datatable-header"fBl><"datatable-scroll-wrap"t><"datatable-footer"ip>',
      language: {
        search: '<span>_FILTER_LABEL_</span> _INPUT_',
        lengthMenu: '<span>_SHOW_LABEL_</span> _MENU_',
        paginate: { 'first': 'First', 'last': 'Last', 'next': '&rarr;', 'previous': '&larr;' }
      }
    });


    // Column selectors
    let table = $('.table').DataTable({
      buttons: {
        buttons: [
          {
            extend: 'excelHtml5',
            className: 'btn btn-default',
            exportOptions: {
              columns: ':visible'
            }
          }
        ]
      }
    });

    // Add placeholder to the datatable filter option
    $('.dataTables_filter input[type=search]').attr('placeholder', _FILTER_PLACEHOLDER_);

    // Enable Select2 select for the length option
    $('.dataTables_length select').select2({
      minimumResultsForSearch: Infinity,
      width: 'auto'
    });

    return table;

  }

}

【问题讨论】:

    标签: javascript jquery angular angular2-template typescript2.0


    【解决方案1】:

    在获取数据后尝试这样做

    ngOnInit(): void {
        let self = this;
        this.translate.getData().subscribe((records) => {
          this.data = records;
          self.instantiateDataTable();
        });
    }
    

    【讨论】:

    • 我试过这个解决方案,同样的问题。数据表插件提醒数据不可用。
    • 你看过primeng数据表了吗?这似乎比使用 jquery 插件更好。 primefaces.org/primeng/#/datatable
    • 或者将代码从 ngOnInit 移动到 ngAfterViewInit
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多