数据表在保存时不刷新

时间:2018-03-20 06:35:15

标签: ajax angular datatable smartadmin

我希望我的表在保存点击时刷新,它适用于带有* ngFor的普通表,但我正在使用Smartadmin角度模板。我认为解决方案可能与table.ajax.reload()有关,但我如何以角度方式执行此操作。

保存-tax.component.ts

int i = 0;
while ( a[i] && a[i] != ":") i++; // loop ends when a[i] is NULL or a[i] is ":"
char *b = &a[i];
printf("%s", b);

datatable.component.ts

import { Component, OnInit, Input ,Output, EventEmitter } from '@angular/core';
// Forms related packages
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { FormValidation } from 'app/shared/validators/formValidation'; //custom form validation 
import { ConfigurationService } from 'app/+configuration/configuration.service';
import { FlashMessagesService } from 'angular2-flash-messages';


@Component({
  selector: 'save-tax',
  templateUrl: './save-tax.component.html'
})
export class SaveTaxComponent implements OnInit {

  @Output() reloadTableData = new EventEmitter();

  saveTaxForm: FormGroup;
  constructor(private _fb: FormBuilder,
    private _config: ConfigurationService,
    private _flash: FlashMessagesService) { }

  ngOnInit() {
    this.saveTaxForm_builder();
  }

  saveTaxForm_builder() {
    this.saveTaxForm = this._fb.group({
      tax_title: [null, [
        Validators.required
      ]],
      tax_rate: [null, [
        Validators.required,
        Validators.pattern(FormValidation.patterns().price),
      ]],
    });
  }

  tTitle = "input"; tRate = "input";

  validInput(val) {
    var classSuccess = "input state-success";
    val == 'tax_title' ? this.tTitle = classSuccess : null;
    val == 'tax_rate' ? this.tRate = classSuccess : null;
  }

  invalidInput(val) {
    var classError = "input state-error";
    val == 'tax_title' ? this.tTitle = classError : null;
    val == 'tax_rate' ? this.tRate = classError : null;
  }

  classReset() {
    this.tTitle = "input";
    this.tRate = "input";
  }

  save_tax() {
    if (this.saveTaxForm.value) {
      this._config.createTax(this.saveTaxForm.value).subscribe(data => {
        if (data.success) {        
          this._flash.show(data.msg, { cssClass: 'alert alert-block alert-success', timeout: 1000 });            
          this.saveTaxForm.reset();
          this.classReset();         
          this.reloadTableData.emit(); // Emitting an event  
        } else {
          this.saveTaxForm.reset();
          this.classReset();
          this._flash.show(data.msg, { cssClass: 'alert alert-block alert-danger', timeout: 3500 });
        }
      },
        error => {
          this.saveTaxForm.reset();
          this.classReset();
          this._flash.show("Please contact customer support. " + error.status + ": Internal server error.", { cssClass: 'alert alert-danger', timeout: 5000 });
        });
    } else {
      this._flash.show('Something went wrong! Please try again..', { cssClass: 'alert alert-warning', timeout: 3000 });
    }
  }

}

税收list.component.html

import {Component, Input, ElementRef, AfterContentInit, OnInit} from '@angular/core';

declare var $: any;

@Component({

  selector: 'sa-datatable',
  template: `
      <table class="dataTable responsive {{tableClass}}" width="{{width}}">
        <ng-content></ng-content>
      </table>
`,
  styles: [
    require('smartadmin-plugins/datatables/datatables.min.css')
  ]
})
export class DatatableComponent implements OnInit {

  @Input() public options:any;
  @Input() public filter:any;
  @Input() public detailsFormat:any;

  @Input() public paginationLength: boolean;
  @Input() public columnsHide: boolean;
  @Input() public tableClass: string;
  @Input() public width: string = '100%';

  constructor(private el: ElementRef) {
  }

  ngOnInit() {
    Promise.all([
      System.import('script-loader!smartadmin-plugins/datatables/datatables.min.js'),
    ]).then(()=>{
      this.render()

    })
  }

  render() {
    let element = $(this.el.nativeElement.children[0]);
    let options = this.options || {}


    let toolbar = '';
    if (options.buttons)
      toolbar += 'B';
    if (this.paginationLength)
      toolbar += 'l';
    if (this.columnsHide)
      toolbar += 'C';

    if (typeof options.ajax === 'string') {
      let url = options.ajax;
      options.ajax = {
        url: url,
        complete: function (xhr) {
           options.ajax.reload();
        }
      }
    }

    options = $.extend(options, {

      "dom": "<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-12 hidden-xs text-right'" + toolbar + ">r>" +
      "t" +
      "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
      oLanguage: {
        "sSearch": "<span class='input-group-addon'><i class='glyphicon glyphicon-search'></i></span> ",
        "sLengthMenu": "_MENU_"
      },
      "autoWidth": false,
      retrieve: true,
      responsive: true,
      initComplete: (settings, json)=> {
        element.parent().find('.input-sm', ).removeClass("input-sm").addClass('input-md');
      }
    });

    const _dataTable = element.DataTable(options);

    if (this.filter) {
      // Apply the filter
      element.on('keyup change', 'thead th input[type=text]', function () {
        _dataTable
          .column($(this).parent().index() + ':visible')
          .search(this.value)
          .draw();

      });
    }
  //custom functions 
  element.on('click', 'delete', function () {
    var tr = $(this).closest('tr');
    var row = _dataTable.row( tr );

    if ( $(this).hasClass('delete') ) {
          row.remove().draw(false);
          console.log(row);
    }
    else {
      //$(table).$('tr.selected').removeClass('selected');
      $(this).addClass('selected');
    }
    console.log($(this).attr("class"))
  });

  //end custom functions

    if (!toolbar) {
      element.parent().find(".dt-toolbar").append('<div class="text-right"><img src="assets/img/logo.png" alt="SmartAdmin" style="width: 111px; margin-top: 3px; margin-right: 10px;"></div>');
    }

    if(this.detailsFormat){
      let format = this.detailsFormat
      element.on('click', 'td.details-control', function () {
        var tr = $(this).closest('tr');
        var row = _dataTable.row( tr );
        if ( row.child.isShown() ) {
          row.child.hide();
          tr.removeClass('shown');
        }
        else {
          row.child( format(row.data()) ).show();
          tr.addClass('shown');
        }
      })
    }


  }

}

税收list.component.ts

<!-- NEW COL START -->
<article class="col-sm-12 col-md-12 col-lg-12">
  <!-- Widget ID (each widget will need unique ID)-->
  <div sa-widget [editbutton]="false" [custombutton]="false">
      <header>
          <span class="widget-icon"> <i class="fa fa-percent"></i> </span>
          <h2>Tax Rule List</h2>
      </header>
      <!-- widget div-->
      <div>
          <!-- widget content -->
          <div class="widget-body no-padding">
            <sa-datatable [options]="tableData"  paginationLength="true" tableClass="table table-striped table-bordered table-hover" width="100%">
                <thead>
                    <tr>
                        <th data-hide="phone"> ID </th>
                        <th data-hide="phone,tablet">Tax Title</th>
                        <th data-class="expand">Tax Rate</th>
                        <th data-hide="phone,tablet">Status</th>
                        <th data-hide="phone,tablet"> Action </th>
                    </tr>
                </thead>
            </sa-datatable>
          </div>
          <!-- end widget content -->
      </div>
      <!-- end widget div -->
  </div>
  <!-- end widget -->
</article>
<!-- END COL -->

1 个答案:

答案 0 :(得分:0)

您可以使用<div class='widget-toolbar'>...</div>并使用(click)事件绑定在窗口小部件中添加刷新按钮,并附加方法。我将其命名为onRefresh() ...

<div sa-widget [editbutton]="false" [colorbutton]="false">
              <header>
                <span class="widget-icon">
                  <i class="fa fa-chart"></i>
                </span>
                <h2>Sample Datatable</h2>
                <div class="widget-toolbar" role="menu">
                  <a class="glyphicon glyphicon-refresh" (click)="onRefresh('#studentTable table')"></a>
                </div>
              </header>
              <div>
                <div class="widget-body no-padding">
                  <sa-datatable id="studentTable" [options]="datatableOptions" tableClass="table table-striped table-bordered table-hover table-responsive">
                    <thead>
                      <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Rank</th>
                        <th>Options</th>
                      </tr>
                    </thead>
                  </sa-datatable>
                </div>
              </div>
            </div>

关注我在click事件绑定中给出的方法,我传递了<sa-datatable>的{​​{1}}的id,即table根据提到的表{tag} smartadmin的数据表实现。

现在在组件中,添加一个方法'onRefresh()',它应该像

#studentTable table

在此方法中,onRefresh(id: any) { if ($.fn.DataTable.isDataTable(id)) { const table = $(id).DataTable(); table.ajax.reload(); } } 将出现在此id中,该id是方法中的参数。使用#studentTable table,您可以执行jQuery。 但是你需要在顶部声明jQuery。

table.ajax.reload()

app.component.ts

declare var $ : any;