0

I am new to Angular.

Can you explain me how the transform function works for example in this example: search input field in angular?

in first answer one has:

transform(value: any, searchValue): any {
    if (!searchValue) return value;
    return value.filter((v) => 
    v.name.toLowerCase().indexOf(searchValue.toLowerCase()) > -1 || 
    v.size.toLowerCase().indexOf(searchValue.toLowerCase()) > -1)

  }

What does this code do?

if (!searchValue) return value;
PabloPhones
  • 123
  • 1
  • 1
  • 9
  • OK. I got it: value are all objects I am checking, searchvalue is my filter value. if (!searchValue) return value; - if the seachvalue is false, please return all values so no change. – PabloPhones Apr 18 '20 at 12:18
  • OK. And these code? ```return value.filter((v) => v.name.toLowerCase().indexOf(searchValue.toLowerCase()) > -1 || v.size.toLowerCase().indexOf(searchValue.toLowerCase()) > -1) ``` – PabloPhones Apr 18 '20 at 12:25

4 Answers4

0

If the searchValue is null then this condition always returns the value, but if there is something in it, the pipe return the values that their name and/or size contains the search value.

so on that example if the searchvalue is empty it displays all the folderObjs but for example if searchValue='a' it only shows the folders that their name or size contains 'a';

Ehsan Kiani
  • 3,050
  • 1
  • 17
  • 19
0

if searchvalue is falsy then return original value aka array[]. Falsy means when you pass empty string and no value in search field;

Value is array and it will filter based on searchValue. whatever the name in value array let me make it lower case and also searchValue to lowercase then find with indexOf if it is greater than > -1 that means we found match and return filtered array.

Indraraj26
  • 1,726
  • 1
  • 14
  • 29
0

You should put an additional argument for this pipe. For example:

{{ value | app-pipe:searchValue }}

If you don't put an additional argument, pipe will return value.

Aleksey
  • 36
  • 1
  • 2
0

Your pipe transform method have 2 arguments value and searchValue. it checks your searchValue is falsy . if it is falsy it will return the value parameter as it is. else it will filter the value array based on the searchValue passed. filtering is done by checking the name or size(converted to lowercase) field of each item of the value array is containing the searchValue.

Note : There are only six falsy values in JavaScript: undefined, null, NaN, 0, "" (empty string), and false

To use the pipe in template

{{ value | pipename:searchValue }}

pipename - is your pipe name
value - is the first argument to your transform method
searchValue - is the second argument of your transform method

Sayooj V R
  • 2,255
  • 2
  • 11
  • 23