filter-rows
Description
Fires when filtering dataUsage
"filter-rows": ({
filter?: any,
key?: string,
value?: any,
}) => boolean|void;
Parameters
The callback of the action takes an object with the following parameters:
filter
- (optional) any filtering function that takes each item from the data array and returns true or false for each itemkey
- (optional) field namevalue
- (optional) filter value
Example
The example below demonstrates how to apply built-in filters, track the filter-rows
action and output the field name (key) that is filtered:
<script>
import { Grid } from "wx-svelte-grid";
import { getData } from "../data";
const { allData, data, countries } = getData();
const columns = [
{ id: "id", width: 50 },
{
id: "firstName",
header: { filter: "text" },
footer: "First Name",
width: 150,
},
{
id: "lastName",
header: { filter: { type: "text" } },
footer: "Last Name",
width: 150,
},
{
id: "email",
header: "Email",
footer: "Email",
},
{
id: "country",
header: {
filter: {
type: "richselect",
config: {
options: countries,
},
},
},
options: countries,
},
{
id: "stars",
header: "Stars",
footer: "Stars",
filter: { type: "text" },
},
];
function init(api){
api.on("filter-rows", (ev) => {
console.log("Filtered field:", ev.key);
});
}
</script>
<Grid data={allData} {columns} {init} />
In the next example the filter is applied to the rows whenever a user enters the value in the input field. The applyFilter() function is created to filter the rows by the selected city. The function is assigned to filter
that is then triggered via the api.exec()
method.
<script>
import { Grid } from "wx-svelte-grid";
const data = [
{ id: 1, firstName: "John", lastName: "Doe", city: "New York" },
{ id: 2, firstName: "Jane", lastName: "Smith", city: "Los Angeles" },
{ id: 3, firstName: "Mike", lastName: "Jordan", city: "Chicago" },
{ id: 4, firstName: "Emily", lastName: "Davis", city: "New York" },
];
const columns = [
{ id: "firstName", name: "First Name" },
{ id: "lastName", name: "Last Name" },
{ id: "city", name: "City" },
];
let api = $state();
let filterCity = $state("New York");
function filterRowsByCity(city) {
return (item) => item.city.toLowerCase() === city.toLowerCase();
}
function applyFilter(city) {
if (api) {
const filter = filterRowsByCity(city);
api.exec("filter-rows", { filter });
}
}
// Apply filter automatically whenever the filterCity changes
$effect(() => {
if (filterCity && api)
applyFilter(filterCity);
});
</script>
<input type="text" bind:value={filterCity} placeholder="Filter by City" />
<Grid {data} {columns} bind:this={api} />
Related articles: