4

I'm using ngx-datatable and I tried to add filter ability to my code but it dosen't work at all.

This is my code :

import {Component, OnInit, ViewChild, ViewEncapsulation} from '@angular/core';
import {NavbarService} from '../../Services/navbar.service';
import {DataService} from '../../Services/data.service';
import {DatatableComponent} from '@swimlane/ngx-datatable';
import {forEach} from '@angular/router/src/utils/collection';

@Component({
  selector: 'app-student',
  templateUrl: './student.component.html',
  styleUrls: ['./student.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class StudentComponent implements OnInit {
  rows: Student[];
  @ViewChild('myTable') table: any;

  students: Student[];
  temp = [];

  constructor(private nav: NavbarService, public dataService: DataService) {
    this.dataService.getStudents().subscribe(Students => {
      this.Students = [...Students];
      this.rows = Students;
    });
  }

  ngOnInit() {
    this.nav.show();
  }

  onPage(event: Event) {
    clearTimeout(this.timeout);
    this.timeout = setTimeout(() => {
      console.log('paged!', event);
    }, 100);
  }

  toggleExpandRow(row) {
    console.log('Toggled Expand Row!', row);
    this.table.rowDetail.toggleExpandRow(row);
  }

  onDetailToggle(event) {
    console.log('Detail Toggled', event);
  }

  updateFilter(event) {
    const val = event.target.value.toLowerCase();
    this.rows = this.students.filter(row =>
      row.AspNetUsers.Nom.toLowerCase().indexOf(val) !== -1 || !val
    );
    this.table.offset = 0;
  }
}

like in the documentation code , I have to add a function to my input updateFilter that take the value of input and then there is a function that filter temporary array depending on the value inserted but this function doesn't work at all I get Cannot read property 'Name' of undefined I checked the value of they array using console and debug it seems the array is correct and have values but I don't know why the filter function returns nothing. I tried add try - catch the problem disappears but the filter function filter nothing.

EDIT : Code of student.component.html

<div class="container">
  <div class="row">
    <div class="col">
      <form>
        <div class="input-group">
          <input class="form-control" id="search"  name="search" (keyup)='updateFilter($event)' placeholder="Rechercher">
          <div class="input-group-addon"><i class="material-icons">search</i></div>
        </div>
      </form>
    </div>
  </div>
  <div class="row mt-3">
    <div class="col">
      <ngx-datatable
        #myTable
        class='material expandable'
        [columnMode]="'force'"
        [headerHeight]="50"
        [footerHeight]="50"
        [rowHeight]="50"
        [rows]='rows'
        [limit]="20"
        (page)="onPage($event)">

        <ngx-datatable-row-detail [rowHeight]="120" #myDetailRow (toggle)="onDetailToggle($event)">
          <ng-template let-row="row" let-expanded="expanded" ngx-datatable-row-detail-template>
            <div class="container">
              <table class="table">
                <tr>
                  <th>Email</th>
                  <td>{{row.AspNetUsers.Email}}</td>
                </tr>
                <tr>
                  <th>Adresse</th>
                  <td>{{row.ADRESSE}}</td>
                </tr>
              </table>
            </div>
          </ng-template>
        </ngx-datatable-row-detail>

        <ngx-datatable-column
          [width]="50"
          [resizeable]="false"
          [sortable]="false"
          [draggable]="false"
          [canAutoResize]="false">
          <ng-template let-row="row" let-expanded="expanded" ngx-datatable-cell-template>
            <a
              href="javascript:"
              [class.datatable-icon-right]="!expanded"
              [class.datatable-icon-down]="expanded"
              title="Expand/Collapse Row"
              (click)="toggleExpandRow(row)">
            </a>
          </ng-template>
        </ngx-datatable-column>

        <ngx-datatable-column name="ID" [width]="100">
          <ng-template let-row="row" ngx-datatable-cell-template>
            {{row.studentID}}
          </ng-template>
        </ngx-datatable-column>

        <ngx-datatable-column name="First Name" [width]="100">
          <ng-template let-row="row" ngx-datatable-cell-template>
            {{row.AspNetUsers.Name}}
          </ng-template>
        </ngx-datatable-column>

        <ngx-datatable-column name="Last Name" [width]="100">
          <ng-template let-row="row" ngx-datatable-cell-template>
            {{row.AspNetUsers.LastName}}
          </ng-template>
        </ngx-datatable-column>

        <ngx-datatable-column name="Special Code" [width]="100">
          <ng-template let-row="row" ngx-datatable-cell-template>
            {{row.AspNetUsers.SpecialCode}}
          </ng-template>
        </ngx-datatable-column>


        <ngx-datatable-column name="PhoneNumber" [width]="100">
          <ng-template let-row="row" ngx-datatable-cell-template>
            {{row.AspNetUsers.PhoneNumber}}
          </ng-template>
        </ngx-datatable-column>

      </ngx-datatable>
    </div>
  </div>
</div>

Edit 2 : I found out why I get the error , there is some missing names (they are null) and inside filter the problem happens if it's null. I added student !== null but still the problems happens.

Noah13
  • 337
  • 4
  • 13
  • please add your `students.component.html` code also, so we can understand the logic properly – Kanso Code Sep 04 '17 at 22:53
  • 1
    thank you for suggestion , I added the code of students.component.html – Noah13 Sep 04 '17 at 22:59
  • What is the value of `this.rows` after filtering? could you log `this.rows` above this line - `this.table.offset = 0;`? – Kanso Code Sep 04 '17 at 23:03
  • when I get the error of `Cannot read property 'Name' of undefined` the code stops and I can't access this.rows nor `this.table.offset=0` is executed (I tried both log and debug both ) – Noah13 Sep 04 '17 at 23:05

1 Answers1

1

It is obviously an error in the HTML which breaks your filtering. Put safe navigation operator into each interpolation of the row like:

{{row.AspNetUsers?.Name}}
{{row.AspNetUsers?.SpecialCode}}

And so on. Should remove the error, so you will able to debug more deeply.

Kanso Code
  • 7,479
  • 5
  • 34
  • 49
  • I did already try this solution both using `row?.AspNetUsers?.Name` & yours but it dosen't work at all I still get the error / Note that using try catch and normal for loop the code works without problem. – Noah13 Sep 04 '17 at 23:14
  • @Kareem13, that's weird, in your code I see the only one place where the logic tries to reach 'Name' property of something. So if you can find where else that happens, or provide plunker, that would be very useful. – Kanso Code Sep 04 '17 at 23:17
  • Yes I know , when I use traditional for loop and try/catch the code works without any problem. another thing when I use row.ADRESSE instead of row.AspNetUsers.Name I get another error `cannot read property 'tolowercase' of null` so I don't know really I'm sure the object have values but either I get null or undefined – Noah13 Sep 04 '17 at 23:25
  • I double checked the code and I found out the I have some "name" that contains null (from API) I added code studient.AspNetUsers.Name !== null but I still get the error when I delete data that is null from server the filtering works without problems. – Noah13 Sep 05 '17 at 01:05