0

I'm attempting to create a sort a basic table using Angular.

To setup the table I use:

<table id="tableSortExample" mdbTable class="z-depth-1">
  <thead>
  <tr>
    <th (click)="sort('One')">One</th>
    <th (click)="sort('Two')">Two</th>
    <th (click)="sort('Three')">Three</th>
    <th (click)="sort('Four')">Four</th>
  </tr>
  </thead>
  <tbody>
  <tr *ngFor="let el of elements; let i = index">
    <th scope="row">{{el.id}}</th>
    <td>{{el.first}}</td>
    <td>{{el.last}}</td>
    <td>{{el.handle}}</td>
  </tr>
  </tbody>
</table>

and then define in the component:

  sort(colName) {
    console.log('sort clicked : ' + colName);
    this.elements.sort((a, b) => a[colName] > b[colName] ? 1 : a[colName] < b[colName] ? -1 : 0)
  }
  // tslint:disable-next-line:typedef
  ngOnInit() {
    for (let i = 1; i <= 11; i++) {
      this.elements.push({
        id: i,
        first: 'test',
        last: 'Name ' + i,
        handle: 'Handle ' + i
      });
    }
  }

On opening the page that contains the HTML the table is rendered :

enter image description here

But clicking the column headers does not apply the sort.

The function sort is fired on click as can see messages printed to the log:

console.log('sort clicked : ' + colName);

I'm attempting to work from a previously answered question but it seems I've missed a step or not understood something.

How to enable sort of the columns ?

1 Answer 1

1

The keys in the elements array are: id, first, last, and handle

Replace the arguments in the sort functions called.

<th (click)="sort('id')">One</th>
<th (click)="sort('first')">Two</th>
<th (click)="sort('last')">Three</th>
<th (click)="sort('handle')">Four</th>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.