MasterX
MasterX

Reputation: 91

Null value breaking the custom filters in Mat Table

I'm adding multiple custom filters to Mat-Table.

Issue is when the data is have an null value entire filter functionality is breaking.

My Sample Mock

{
  name: null,
  id: 1,
  colour: 'Green',
  pet: 'Dog'
},

In customFilter() function I'm filter the data like below,

 data.name.toLowerCase().indexOf(searchTerms.name) !== -1

I tried adding like this data?.name but no luck.

Link to my Stackblitz https://stackblitz.com/edit/material-column-filter-ov6ut6?file=src/app/app.component.ts

Please help.

Upvotes: 0

Views: 1105

Answers (2)

Benny Halperin
Benny Halperin

Reputation: 2322

More elegant condition:

(data.name || '').toLowerCase().includes(searchTerm.name.toLowerCase())

Upvotes: 2

LearningEveryday
LearningEveryday

Reputation: 584

Try this:

let names = [
    {
  "name": null,
  "id": 1,
  "colour": "Green",
  "pet": "Dog"
},
       {
  "name": "Hello",
  "id": 2,
  "colour": "Green",
  "pet": "Dog"
},
        {
  "name": "Not null",
  "id": 3,
  "colour": "Green",
  "pet": "Dog"
}
];

let filterArray = names.filter((name1) => {return name1.name && name1.name.toLowerCase().indexOf('ello') > -1});
console.log(filterArray);

You have to add a null check and index of check in your filter condition.

Upvotes: 0

Related Questions