简体   繁体   中英

Elegant way to apply jquery plugin in Angular2

I fetch data from webservice in ngOnInit block and then i need to apply jquery data table plugin (this action i performed both in ngAfterViewInit and ngAfterContentInit). The problem is that jquery datatable plugin don't see data in the component table which was fetched in ngOnInit block. The only way I could implement this is setTimeout or setInterval (which stops execution if plugin instance created).

Is there any other method to perform task I try to ?

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;

  }

}

Try doing it after the data was fetched

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM