0

I am trying to use DataTables in an angular 2 project. Please see my code below on how I implement it.

.ts

declare var $:any;
users: UserModel[];
public dataTable: DataTable;

ngOnInit() {
    this.getUsers();
  }

  getUsers() {
this.us.getUsers()
  .subscribe((data:any)=>{
    this.users = data;

    var table=$('#datatables').DataTable({
      "pagingType": "full_numbers",
      "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
      responsive: true,
      language: {
      search: "_INPUT_",
      searchPlaceholder: "Search records",
      }
   });
  });
  }

.html

<table id="datatables" class="table table-striped table-no-bordered table-hover" cellspacing="0" width="100%" style="width:100%">
    <thead>
        <tr>
            <th>Id</th>
            <th>FirstName</th>
            <th>MiddleName</th>
            <th>LastName</th>
            <th>UserName</th>
            <th>Email </th>
            <th>IsActivated </th>
            <th>DateAdded</th>
            <!-- <th class="text-right">{{ tableData1.headerRow[4] }}</th>
              <th class="text-right">{{ tableData1.headerRow[5] }}</th> -->
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let user of users">
            <td class="text-center">{{user.Id}}</td>
            <td>{{user.FirstName}}</td>
            <td>{{user.MiddleName}}</td>
            <td>{{user.LastName}}</td>
            <td>{{user.UserName}}</td>
            <td>{{user.Email}}</td>
            <td>{{user.IsActivated}}</td>
        </tr>
    </tbody>
</table>

I can get the data and render it in the table but when I use the filter, all of the data goes away. When I remove the characters from the search box, I cannot get the data back. Even when I use the sorter arrow, I get the same issue. Can you please show me how to do this right. Thank you.

1 Answer 1

1

I just reproduced your problem on stackblitz. Seems like there is and issue with using ngFor in with jQuery datatable. I fixed this issue by providing this.users as data argument of the datatable along with columns and removing the <tbody> section from the html. As i did not have the service to get users, i created a users array in the component and generated datatable for it. Please do as i did, and your datatable will work fine. Link: Working Datatable Stackblitz

Sign up to request clarification or add additional context in comments.

3 Comments

I have used your suggestion but still a no go. Please see my edit. Thank you.
THANK YOU SOOOOOOOOO MMMMMMUUUUCCCHHHHH!!! I have been trying to solve this for 3 days now!!
I have another question Sir. If you have time to answer it. "stackoverflow.com/questions/53079061/…"

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.