Blazor Query Builder Overview
The Ignite UI for Blazor Query Builder provides a rich UI that allows developers to build complex data filtering queries for a specified data set. With this component, you can build an expression tree and specify AND/OR conditions between expressions, with editors and condition lists determined by each field’s data type. The expression tree can then be easily transformed to a query in a format the backend supports.
Getting started with Blazor Query Builder
To start using the IgbQueryBuilder, first, you need to install the Ignite UI for Blazor package by running the following command:
dotnet add package IgniteUI.Blazor --version 26.1.98
Register the Query Builder module in the Program.cs file:
builder.Services.AddIgniteUIBlazor(typeof(IgbQueryBuilderModule));
You also need to reference the corresponding styles based on your project configuration.
<link href="_content/IgniteUI.Blazor/themes/light/bootstrap.css" rel="stylesheet" />
Using the Blazor Query Builder
If no expression tree is initially set, you start by choosing an entity and which of its fields the query should return. After that, conditions or sub-groups can be added.
In order to add a condition you select a field, an operand based on the field data type and a value if the operand is not unary. The operands In and Not In will allow you to create an inner query with conditions for a different entity instead of simply providing a value. Once the condition is committed, a chip with the condition information appears. By clicking or hovering the chip, you have the options to modify it or add another condition or group right after it.
Clicking on the (AND or OR) button placed above each group, will open a menu with options to change the group type or ungroup the conditions inside.
Since every condition is related to a specific field from a particular entity changing the entity will lead to resetting all preset conditions and groups.
You can start using the component by setting the Entities property to an array describing the entity name and an array of its fields, where each field is defined by its name and data type. Once a field is selected it will automatically assign the corresponding operands based on the data type.
The Query Builder has the ExpressionTree property. You could use it to set an initial state of the control and access the user-specified filtering logic.
<IgbQueryBuilder @ref="queryBuilder"
Entities="Entities"
ExpressionTree="ExpressionTree"
ExpressionTreeChangeScript="WebQueryBuilderExpressionTreeChange">
</IgbQueryBuilder>
@code {
private static readonly IgbFieldType[] OrderFields =
[
new() { Field = "orderId", DataType = GridColumnDataType.Number },
new() { Field = "customerId", DataType = GridColumnDataType.String },
new() { Field = "orderDate", DataType = GridColumnDataType.Date }
];
private static readonly IgbEntityType[] Entities =
[
new() { Name = "Orders", Fields = OrderFields }
];
private static readonly IgbExpressionTree ExpressionTree = new()
{
FilteringOperands = [],
Operator = FilteringLogic.And,
Entity = "Orders"
};
private IgbQueryBuilder queryBuilder;
}
The IgbExpressionTree is a bindable property which means you can use ExpressionTreeChangeScript to receive notifications when the end-user changes the UI by creating, editing or removing conditions.
// In JavaScript
igRegisterScript("WebQueryBuilderExpressionTreeChange", (evtArgs) => {
const expressionTree = evtArgs.detail;
console.log("Expression tree changed:", expressionTree);
}, false);
Expressions Dragging
Condition chips can be easily repositioned using mouse Drag & Drop or Keyboard reordering approaches. With those, users can adjust their query logic dynamically.
- Dragging a chip does not modify its condition/contents, only its position.
- Chip can also be dragged along groups and subgroups. For example, grouping/ungrouping expressions is achieved via the Expressions Dragging functionality. In order to group already existing conditions, first you need to add a new group through the ‘add’ group button. Then via dragging, the required expressions can be moved to that group. In order to ungroup, you could drag all conditions outside their current group and once the last condition is moved out, the group will be deleted.
Chips from one query tree cannot be dragged in another, e.g. from parent to inner and vice versa.
Keyboard interaction
Key Combinations
- Tab / Shift + Tab - navigates to the next/previous chip, drag indicator, remove button, ‘add’ expression button.
- Arrow Down/Arrow Up - when chip’s drag indicator is focused, the chip can be moved up/down.
- Space / Enter - focused expression enters edit mode. If chip is been moved, this confirms it’s new position.
- Esc - chip’s reordering is canceled and it returns to it’s original position.
Keyboard reordering provides the same functionality as mouse Drag & Drop. Once a chip is moved, user has to confirm the new position or cancel the reorder.
Templating
The Ignite UI for Blazor Query Builder allows defining templates for the component’s header and search value:
Header Template
By default the IgbQueryBuilder header would not be displayed. In order to define such, the IgbQueryBuilderHeader component should be added inside the query builder.
<IgbQueryBuilder Entities="Entities" ExpressionTree="ExpressionTree">
<IgbQueryBuilderHeader Title="My Query Builder"></IgbQueryBuilderHeader>
</IgbQueryBuilder>
Search Value Template
For Blazor, use the SearchValueTemplateScript property to reference a client-side function registered with igRegisterScript.
When using SearchValueTemplate, you must provide templates for all field types in your entity, or the query builder will not function correctly. It is mandatory to implement a default/fallback template that handles any fields or conditions not covered by specific custom templates. Without this, users will not be able to edit
conditions for those fields.
<IgbQueryBuilder @ref="queryBuilder"
Entities="Entities"
ExpressionTree="ExpressionTree"
ExpressionTreeChangeScript="WebQueryBuilderExpressionTreeChange"
SearchValueTemplateScript="SearchValueTemplate">
<IgbQueryBuilderHeader Title="Query Builder Template Sample"></IgbQueryBuilderHeader>
</IgbQueryBuilder>
// In JavaScript
igRegisterScript("SearchValueTemplate", (ctx) => {
const field = ctx.selectedField?.field;
const condition = ctx.selectedCondition;
const matchesEqualityCondition = condition === "equals" || condition === "doesNotEqual";
if (!ctx.implicit) {
ctx.implicit = { value: null };
}
if (field === "Region" && matchesEqualityCondition) {
return buildRegionSelect(ctx);
}
if (field === "OrderStatus" && matchesEqualityCondition) {
return buildStatusRadios(ctx);
}
if (ctx.selectedField?.dataType === "date") {
return buildDatePicker(ctx);
}
if (field === "RequiredTime") {
return buildTimeInput(ctx);
}
return buildDefaultInput(ctx, matchesEqualityCondition);
}, false);
Below are examples showing one template for each type of editor:
For the Region Select example:
// Field definition
new() { Field = "Region", DataType = GridColumnDataType.String }
// In JavaScript
// Template
function buildRegionSelect(ctx) {
const currentValue = ctx?.implicit?.value;
const changeHandler = (event) => {
const value = event && event.detail ? event.detail.value : null;
ctx.implicit.value = value;
};
return html`
<igc-select
placeholder="Region"
.value=${currentValue}
@igcChange=${changeHandler}>
${regionOptions.map(option => html`
<igc-select-item value=${option.value}>${option.text}</igc-select-item>
`)}
</igc-select>
`;
}
For the Status Radio Group example:
// Field definition
new() { Field = "OrderStatus", DataType = GridColumnDataType.String }
// In JavaScript
// Template
function buildStatusRadios(ctx) {
const implicitValue = ctx?.implicit?.value;
const currentValue = implicitValue == null ? '' : implicitValue.toString();
const changeHandler = (event) => {
const value = event && event.detail ? event.detail.value : undefined;
if (!value || ctx.implicit.value === value) {
return;
}
ctx.implicit.value = value;
};
return html`
<igc-radio-group
style="gap: 5px;"
.alignment=${"horizontal"}
.value=${currentValue}
@igcChange=${changeHandler}>
${statusOptions.map(option => html`
<igc-radio
name="status"
value=${option.value}
?checked=${option.value.toString() === currentValue}>
${option.text}
</igc-radio>
`)}
</igc-radio-group>
`;
}
For the Date Picker example:
// Field definition
new() { Field = "OrderDate", DataType = GridColumnDataType.Date }
// In JavaScript
// Template
function buildDatePicker(ctx) {
const implicitValue = ctx.implicit?.value;
const currentValue = implicitValue instanceof Date
? implicitValue
: implicitValue
? new Date(implicitValue)
: null;
const allowedConditions = ['equals', 'doesNotEqual', 'before', 'after'];
const isEnabled = allowedConditions.includes(ctx.selectedCondition ?? '');
return html`
<igc-date-picker
.value=${currentValue}
.disabled=${!isEnabled}
@click=${(event) => (event.currentTarget).show()}
@igcChange=${(event) => {
ctx.implicit.value = event.detail;
}}>
</igc-date-picker>
`;
}
For the Time Input example:
// Field definition
new()
{
Field = "RequiredTime",
DataType = GridColumnDataType.Time,
DefaultTimeFormat = "hh:mm tt"
}
// In JavaScript
// Template
function buildTimeInput(ctx) {
const currentValue = normalizeTimeValue(ctx.implicit?.value);
const allowedConditions = ['at', 'not_at', 'at_before', 'at_after', 'before', 'after'];
const isDisabled = ctx.selectedField == null || !allowedConditions.includes(ctx.selectedCondition ?? '');
return html`
<igc-date-time-input
.inputFormat=${"hh:mm tt"}
.value=${currentValue}
.disabled=${isDisabled}
@igcChange=${(event) => {
const picker = event.currentTarget;
ctx.implicit.value = picker.value;
}}>
<igc-icon slot="prefix" name="clock" collection="material"></igc-icon>
</igc-date-time-input>
`;
}
For the Default Input template:
// Field definitions for string, number, and boolean types
new() { Field = "ShipCountry", DataType = GridColumnDataType.String }
new() { Field = "OrderID", DataType = GridColumnDataType.Number }
new() { Field = "IsRushOrder", DataType = GridColumnDataType.Boolean }
// In JavaScript
// Template that handles all these types
function buildDefaultInput(ctx, equalityCondition) {
const selectedField = ctx.selectedField;
const dataType = selectedField?.dataType;
const isNumber = dataType === 'number';
const isBoolean = dataType === 'boolean';
const placeholder = ctx.selectedCondition === 'inQuery' || ctx.selectedCondition === 'notInQuery'
? 'Sub-query results'
: 'Value';
const currentImplicitValue = ctx && ctx.implicit ? ctx.implicit.value : null;
const currentValue = typeof currentImplicitValue === 'object' && currentImplicitValue && 'text' in currentImplicitValue
? equalityCondition ? currentImplicitValue.text : ''
: currentImplicitValue;
const inputValue = currentValue == null ? '' : currentValue;
const disabledConditions = ['empty', 'notEmpty', 'null', 'notNull', 'inQuery', 'notInQuery'];
const isDisabled = isBoolean || selectedField == null || disabledConditions.includes(ctx.selectedCondition ?? '');
return html`
<igc-input
.value=${inputValue}
?disabled=${isDisabled}
placeholder=${placeholder}
type=${isNumber ? 'number' : 'text'}
@input=${(event) => {
const target = event.target;
ctx.implicit.value = isNumber
? target.value === '' ? null : Number(target.value)
: target.value;
}}>
</igc-input>
`;
}
Formatter
In order to change the appearance of the search value in the chip displayed when a condition is not in edit mode, you can set a formatter function to the fields array. The search value can be accessed through the value argument as follows:
private static readonly IgbFieldType[] OrderFields =
[
new() { Field = "OrderID", DataType = GridColumnDataType.Number },
new() { Field = "ShipCountry", DataType = GridColumnDataType.String },
new()
{
Field = "OrderDate",
DataType = GridColumnDataType.Date,
PipeArgs = new IgbFieldPipeArgs { Format = "MMM d, y" }
},
new() { Field = "Region", DataType = GridColumnDataType.String }
];
Demo
We’ve created this example to show you the templating and formatter functionalities for the header and the search value of the Blazor Query Builder component.
API References
Additional Resources
Our community is active and always welcoming to new ideas.