Skip to main content

Selecting rows

Marking rows as selected

To mark multiple rows as selected, use the selectedRows property.

Example:

<script>
import { getData } from "./common/data";
import { Grid } from "wx-svelte-grid";

const { data, columns } = getData();

</script>

<Grid {data} {columns} selectedRows={[11,12,15]} />

Enabling multiple selection

The selection of a single row is enabled by default (a row is selected with the right click). To enable the selection of multiple rows using SHIFT or CTRL and the left click, apply the multiselect property and set its value to true.

Example:

<script>
import { Grid } from "wx-svelte-grid";
import { getData } from "./common/data";
const { columns, data } = getData();
</script>

<Grid
{data}
columns}
multiselect={true}
/>

Selecting rows with checkboxes

The example below shows how to select rows by checking Checkboxes within them. Selecting by a row click is disabled.

You can import the ready-made Checkbox control from wx-svelte-core library and apply it to cells. More information about embedding components to cells you can find here: Adding custom content to cells

Such components receive row data and Grid api among $props. Here the select-row action is called using the api.exec() method when the checkbox changes its value.

<script>
import { Checkbox } from "wx-svelte-core";
let { row, api } = $props();

function onChange(ev) {
const { value } = ev;
api.exec("select-row", {
id: row.id,
mode: value,
toggle: true,
});
}
</script>

<div data-action="ignore-click">
<Checkbox onchange={onChange} />
</div>

Now what you need is to import the CheckboxCell component and apply it to cells:

<script>
import { Grid } from "wx-svelte-grid";
import CheckboxCell from "../custom/CheckboxCell.svelte";
import { getData } from "../data";

const { data } = getData();

const columns = [
{ id: "selected", cell: CheckboxCell, width: 36 },
{ id: "city", header: "City", width: 160 },
{ id: "firstName", header: "First Name" },
{ id: "lastName", header: "Last Name" },
{ id: "companyName", header: "Company" },
];
</script>

<div class="demo" style="padding: 20px;">
<div>
<Grid
{data}
{columns}
select={false}
/>
</div>
</div>

Binding checkboxes to selection

The examples below is mostly similar to the above one, but in this case rows can be selected both by clicking on them or checking the checkboxes. Checkbox state changes its state in either ways.

<script>
import { Checkbox } from "wx-svelte-core";

let { row, api } = $props();
//get the array of currently selected rows
const selectedRows = api.getReactiveState().selectedRows;

function onChange(ev) {
const { value } = ev;

api.exec("select-row", {
id: row.id,
mode: value,
toggle: true,
});
}
</script>

<div data-action="ignore-click">
<Checkbox
onchange={onChange}
value={$selectedRows.indexOf(row.id) !== -1} //bind checkbox state to selection
/>
</div>

Related articles: