1

Trying to sort this table but nothing happens when I click sort.

If I move *ngFor into the tr tag, the data disappears when I click sort.

Here's the table I'm using: https://l-lin.github.io/angular-datatables/#/basic/zero-config

<div class="container">
      <div class="row">
        <div class="col-lg-5">
          <h4>Driver's List</h4>
          <table datatable id="driverTable" class="table table-striped">
            <thead class="thead-dark">
              <tr>
                <th scope="col">Name</th>
                <th scope="col">Distance</th>
                <th scope="col">Time</th>
                <th scope="col">View Info</th>
              </tr>
            </thead>
            <tbody *ngFor="let driver of googleDrivers">
              <tr>
                <td>{{driver.Name}}</td>
                <td>{{driver.Distance}}</td>
                <td>{{driver.Duration}}</td>
                <td>Some button</td>
              </tr>
            </tbody>

          </table>
        </div>
        <div class="col-lg-6">
          <h4>Directions:</h4>
          <div #map id="gmap" class="img-responsive"></div>
        </div>
      </div>
    </div>
1
  • can you recreate the issue on stackblitz? that would be helpful. Commented May 6, 2020 at 21:07

1 Answer 1

1

Looking at your issue I assume your googleDrivers list is fetched asynchronously (please provide further code insights if not). If this is the case you have to use a dtTrigger, which simply notifies the table to render after your data fetch. You can do this by simply calling finished by calling next(). See in the docs

In addition you have to use the *ngFor on the <tr> tag.

Example template:

<table datatable id="driverTable" class="table table-striped" [dtTrigger]="dtTrigger">
  <thead class="thead-dark">
  <tr>
    <th scope="col">Name</th>
    <th scope="col">Distance</th>
    <th scope="col">Time</th>
    <th scope="col">View Info</th>
  </tr>
  </thead>
  <tbody>
  <tr *ngFor="let driver of googleDrivers">
    <td>{{driver.Name}}</td>
    <td>{{driver.Distance}}</td>
    <td>{{driver.Duration}}</td>
    <td>Some button</td>
  </tr>
  </tbody>
</table>

A minimal async data load example in your component code:

export class AppComponent implements OnInit {

  public googleDrivers: any[] = [];
  public dtTrigger: Subject<void> = new Subject();

  public ngOnInit(): void {
    this.fetchData().then(data => {
      this.googleDrivers = data;
      this.dtTrigger.next(); // call trigger next() after data loaded
    });
  }
}
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.