mariuszfoltak / angular2-datatable

DataTable - Simple table component with sorting and pagination for Angular2
202 stars 182 forks source link

override Default Sorter and pagination? #63

Open F4Ke opened 7 years ago

F4Ke commented 7 years ago

I want to be able to do some pagination and some sorting myself, using my API. (Otherwise I would have to load around avg~ 30K items for each request)

-> But for that, I need to be able to override the mfDefaultSorter

I have this :

<table class="table  table-hover table-outline mb-0 " [mfData]="items" #mf="mfDataTable" [mfRowsOnPage]="RowsOnPage" >
      <thead class="thead-default">
         <tr>

           <th>
             <mfDefaultSorter by="type">Type</mfDefaultSorter>
           </th>

        </tr>
     .....

so here, the mfDefaultSorter will sort the items by my field 'type'. But now I want it to go in a method of my component.component.ts so I can do the sorting with my API

and with the same ideas, the pagination is done on the loaded items, But I want to be able to do it from my API.

How can I do this ?

QuentinPetel commented 7 years ago

In your HTML:

<table
    #mf="mfDataTable"
    [mfData]="resources"
    [mfRowsOnPage]="per_page"
    [mfSortBy]="sort_field"
    [mfSortOrder]="sort_dir"
    class="table table-striped table-hover">
    <thead>
        <tr>
            <th
                *ngFor="let column of columns; let i = index;" style="text-align: left">
                <mfDefaultSorter by="{{columns[i].name}}" (click)="changeSort(columns[i].name)">{{columns[i].title}}</mfDefaultSorter>
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        ...
    </tbody>
    <tfoot>
    </tfoot>
</table>

In your component.ts :

enum SORT_DIR {
    ASC = <any>'asc',
    DESC = <any>'desc'
}

sort_dir: SORT_DIR = SORT_DIR.DESC;
sort_field: string;

changeSort(field): void {
    if (this.sort_field == field) {
        if (this.sort_dir == SORT_DIR.DESC)
            this.sort_dir = SORT_DIR.ASC;
        else
            this.sort_dir = SORT_DIR.DESC;
    } else {
        this.sort_field = field
        this.sort_dir = SORT_DIR.DESC;
    }

    this.getResources(); // Here you buid your request with sort_dir and sort_field.
}
F4Ke commented 7 years ago

Yes I was thinking on doing it myself like that, thanks for your answer, I'll use that!

Do you have any ideas how to 'override' the page change ?