Home > Software engineering >  How can I filter by the text entered in the filter in PrimeNG?
How can I filter by the text entered in the filter in PrimeNG?

Time:09-29

I have an array strings that I display in a dropdown. I want to filter based on the value entered in the filter field of the dropdown. The issue is I don't know what needs to be entered to the filterBy attribute of the dropdown. I know in case of a class we can enter the properties of the class but what about a string? How can I filter based on the string value itself?

<p-dropdown [options]="example_array_of_strings" [(ngModel)]="selected_string" [filter]="true" filterBy=""</p-dropdown>

I tried tricking it by entering toString() to the filterBy attribute since strings have toString() function too by default, however it didn't work either. How can I specify to filter based on the value of the item instead of some specific property of it?

CodePudding user response:

According to PrimeNG Docs options shall be objects:

An array of objects to display as the available options.

So i guess an easy solution would be to convert your string array into an array of objects for example like so:

selected_string: string;
options: any[];
example_array_of_strings: string[] = ['a', 'b', 'c'];

stringToObject() {
    this.example_array_of_strings.foreach(example_string => {
        this.options.push({ label: example_string });
   });
}

If you call the key "label" the dropdown will automatically take "label" as its optionLabel and its filterBy (if you call it anything other than "label" you have to tell the dropdown what you called it) so you just have to set the optionValue to "label" as well if you want the selected item as a string not an object:

<p-dropdown [options]="options" [(ngModel)]="selected_string" optionValue="label" filter="true"></p-dropdown>

Actually there is a pull request to make filter work with a list of array as options, but i guess it hasn't been accepted. But you can keep an eye on that and maybe filtering a array of strings will work by default in the future.

Hope i could help you :) have a nice day

Max

  • Related