# Angular FilterBuilder Component

FilterBuilder builds a filter as a tree of conditions: groups joined by AND or OR, optionally negated, holding rules and sub-groups. Each field type has its operators and its value editor, the value is a serializable expression, and the exported utilities filter an array in memory, write a readable summary or convert the filter for a Table.

## Basic

FilterBuilder is bound with ngModel and needs the fields the rules can filter on, each with a name , a label and a type . A rule is a field, an operator and a value; the operators and the value editor follow the type of the field. The value is a plain, serializable tree: a group with a logic and its filters , ready to store or to send to an API.

```typescript
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { FilterBuilderExpression, FilterBuilderField, FilterBuilderModule } from '@exhaustive-ui/core/filterbuilder';

@Component({
    template: `
        <div class="card flex flex-col gap-4">
            <p-filter-builder [(ngModel)]="filter" [fields]="fields" ariaLabel="Product filter" />
            <pre class="text-sm font-mono m-0 p-3 rounded-border bg-surface-100 dark:bg-surface-800 overflow-auto">{{ json(filter) }}</pre>
        </div>
    `,
    standalone: true,
    imports: [FormsModule, FilterBuilderModule]
})
export class FilterbuilderBasicDemo {
    fields: FilterBuilderField[] = [
        { name: 'name', label: 'Name', type: 'text' },
        { name: 'price', label: 'Price', type: 'number' },
        { name: 'category', label: 'Category', type: 'select', options: ['Accessories', 'Clothing', 'Electronics', 'Fitness'] }
    ];

    filter: FilterBuilderExpression = {
        logic: 'and',
        filters: [
            { field: 'category', operator: 'equals', value: 'Accessories' },
            { field: 'price', operator: 'lt', value: 100 }
        ]
    };

    json(value: unknown) {
        return JSON.stringify(value, null, 2);
    }
}
```

## Field Types

Each type has its operators and its value editor, built from the form components of the library: text : contains, does not contain, is, is not, starts with, ends with, with an InputText. number : is, is not, is less than, is at most, is greater than, is at least and between, with one or two InputNumbers. date : is, is not, is before, is after and between, with one or two DatePickers, compared by calendar day. boolean : is, with a ToggleSwitch. select : is and is not with a Select, is any of and is none of with a MultiSelect. multiselect : for a field whose data is an array, such as tags: has any of, has none of and is exactly, with a MultiSelect. Every type also has is empty and is not empty . The operators of a field replace the defaults of its type for this field, the operators input replaces them for a whole type, and defaultOperator is selected when the field is picked. The options are label and value pairs, or plain values.

```typescript
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { FilterBuilderExpression, FilterBuilderField, FilterBuilderModule } from '@exhaustive-ui/core/filterbuilder';

@Component({
    template: `
        <div class="card">
            <p-filter-builder [(ngModel)]="filter" [fields]="fields" ariaLabel="Product filter" />
        </div>
    `,
    standalone: true,
    imports: [FormsModule, FilterBuilderModule]
})
export class FilterbuilderFieldtypesDemo {
    fields: FilterBuilderField[] = [
        { name: 'name', label: 'Name', type: 'text', placeholder: 'Product name' },
        { name: 'price', label: 'Price', type: 'number', operators: ['gt', 'lt', 'between'] },
        { name: 'released', label: 'Release date', type: 'date' },
        { name: 'inStock', label: 'In stock', type: 'boolean' },
        {
            name: 'status',
            label: 'Status',
            type: 'select',
            options: [
                { label: 'In stock', value: 'INSTOCK' },
                { label: 'Low stock', value: 'LOWSTOCK' },
                { label: 'Out of stock', value: 'OUTOFSTOCK' }
            ]
        },
        { name: 'tags', label: 'Tags', type: 'multiselect', options: ['new', 'sale', 'eco', 'bestseller'] }
    ];

    filter: FilterBuilderExpression = {
        logic: 'and',
        filters: [
            { field: 'name', operator: 'startsWith', value: 'Bamboo' },
            { field: 'price', operator: 'between', value: [10, 80] },
            { field: 'released', operator: 'after', value: new Date(2026, 0, 1) },
            { field: 'inStock', operator: 'equals', value: true },
            { field: 'status', operator: 'in', value: ['INSTOCK', 'LOWSTOCK'] },
            { field: 'tags', operator: 'in', value: ['eco'] }
        ]
    };
}
```

## Nested Groups

A group joins its rules and sub-groups with AND or OR , and its NOT toggle negates it. Add group adds a sub-group with an empty rule, down to maxDepth levels, the root group being the first one; maxDepth 1 allows no sub-group, and showNot removes the NOT toggles. In the value, a sub-group is an item of filters with its own logic , not and filters .

```typescript
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { FilterBuilderExpression, FilterBuilderField, FilterBuilderModule } from '@exhaustive-ui/core/filterbuilder';

@Component({
    template: `
        <div class="card">
            <p-filter-builder [(ngModel)]="filter" [fields]="fields" [maxDepth]="3" ariaLabel="Order filter" />
        </div>
    `,
    standalone: true,
    imports: [FormsModule, FilterBuilderModule]
})
export class FilterbuilderNestedgroupsDemo {
    fields: FilterBuilderField[] = [
        { name: 'customer', label: 'Customer', type: 'text' },
        { name: 'total', label: 'Total', type: 'number' },
        { name: 'country', label: 'Country', type: 'select', options: ['France', 'Germany', 'Japan', 'United States'] },
        { name: 'paid', label: 'Paid', type: 'boolean' }
    ];

    filter: FilterBuilderExpression = {
        logic: 'and',
        filters: [
            { field: 'total', operator: 'gte', value: 100 },
            {
                logic: 'or',
                filters: [
                    { field: 'country', operator: 'equals', value: 'France' },
                    { logic: 'and', not: true, filters: [{ field: 'paid', operator: 'equals', value: true }] }
                ]
            }
        ]
    };
}
```

## Custom Value Editor

An ng-template with the pFilterBuilderEditor directive replaces the value editor of the fields it names, here a Rating for the rating field; without a name it replaces the editor of every field. The context gives the value as the implicit variable, the field , the operator , a setValue function, the ariaLabel to give to the editor, and the invalid and disabled states.

```typescript
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { FilterBuilderExpression, FilterBuilderField, FilterBuilderModule } from '@exhaustive-ui/core/filterbuilder';
import { RatingModule } from '@exhaustive-ui/core/rating';

@Component({
    template: `
        <div class="card">
            <p-filter-builder [(ngModel)]="filter" [fields]="fields" ariaLabel="Review filter">
                <ng-template pFilterBuilderEditor="rating" let-value let-setValue="setValue" let-ariaLabel="ariaLabel" let-disabled="disabled">
                    <span role="group" [attr.aria-label]="ariaLabel" class="flex items-center min-h-10">
                        <p-rating [ngModel]="value" (ngModelChange)="setValue($event)" [disabled]="disabled" />
                    </span>
                </ng-template>
            </p-filter-builder>
        </div>
    `,
    standalone: true,
    imports: [FormsModule, FilterBuilderModule, RatingModule]
})
export class FilterbuilderTemplateDemo {
    fields: FilterBuilderField[] = [
        { name: 'product', label: 'Product', type: 'text' },
        { name: 'rating', label: 'Rating', type: 'number', operators: ['gte', 'lte', 'equals'] }
    ];

    filter: FilterBuilderExpression = {
        logic: 'and',
        filters: [{ field: 'rating', operator: 'gte', value: 4 }]
    };
}
```

## Filter a Table

filterBuilderToPredicate(expression, fields) turns the value into a function for Array.filter , to filter data in memory, here the rows of a Table. The incomplete rules and the empty groups are ignored, so an empty filter keeps every row; texts are compared without case and accents, dates by calendar day, and the between bounds are included. A dotted field name such as supplier.country reads a nested property, and the resolve option reads the fields in any other way.

```typescript
import { Component, computed, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { FilterBuilderExpression, FilterBuilderField, FilterBuilderModule, filterBuilderToPredicate } from '@exhaustive-ui/core/filterbuilder';
import { TableModule } from '@exhaustive-ui/core/table';
import { TagModule } from '@exhaustive-ui/core/tag';

interface Item {
    name: string;
    category: string;
    price: number;
    stock: number;
    released: string;
    tags: string[];
}

@Component({
    template: `
        <div class="card flex flex-col gap-4">
            <p-filter-builder [ngModel]="filter()" (ngModelChange)="filter.set($event)" [fields]="fields" ariaLabel="Filter of the products" />
            <p class="m-0 text-sm" aria-live="polite">{{ rows().length }} of {{ items.length }} products</p>
            <p-table [value]="rows()" [tableStyle]="{ 'min-width': '40rem' }" size="small">
                <ng-template #header>
                    <tr>
                        <th>Name</th>
                        <th>Category</th>
                        <th>Price</th>
                        <th>Stock</th>
                        <th>Released</th>
                        <th>Tags</th>
                    </tr>
                </ng-template>
                <ng-template #body let-item>
                    <tr>
                        <td>{{ item.name }}</td>
                        <td>{{ item.category }}</td>
                        <td>{{ item.price }}</td>
                        <td>{{ item.stock }}</td>
                        <td>{{ item.released }}</td>
                        <td>
                            <span class="flex gap-1 flex-wrap">
                                @for (tag of item.tags; track tag) {
                                    <p-tag [value]="tag" severity="secondary" />
                                }
                            </span>
                        </td>
                    </tr>
                </ng-template>
                <ng-template #emptymessage>
                    <tr>
                        <td colspan="6">No product matches the filter.</td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [FormsModule, FilterBuilderModule, TableModule, TagModule]
})
export class FilterbuilderTableDemo {
    fields: FilterBuilderField[] = [
        { name: 'name', label: 'Name', type: 'text' },
        { name: 'category', label: 'Category', type: 'select', options: ['Accessories', 'Clothing', 'Electronics', 'Fitness'] },
        { name: 'price', label: 'Price', type: 'number' },
        { name: 'stock', label: 'Stock', type: 'number' },
        { name: 'released', label: 'Released', type: 'date' },
        { name: 'tags', label: 'Tags', type: 'multiselect', options: ['new', 'sale', 'eco'] }
    ];

    items: Item[] = [
        { name: 'Bamboo Watch', category: 'Accessories', price: 65, stock: 24, released: '2026-03-12', tags: ['eco'] },
        { name: 'Black Watch', category: 'Accessories', price: 72, stock: 61, released: '2025-11-02', tags: [] },
        { name: 'Blue Band', category: 'Fitness', price: 79, stock: 2, released: '2026-05-20', tags: ['new'] },
        { name: 'Blue T-Shirt', category: 'Clothing', price: 29, stock: 25, released: '2025-08-14', tags: ['sale'] },
        { name: 'Bracelet', category: 'Accessories', price: 15, stock: 73, released: '2024-12-01', tags: ['sale', 'eco'] },
        { name: 'Brown Purse', category: 'Accessories', price: 120, stock: 0, released: '2026-01-30', tags: [] },
        { name: 'Chakra Bracelet', category: 'Accessories', price: 32, stock: 5, released: '2026-06-08', tags: ['new', 'eco'] },
        { name: 'Galaxy Earrings', category: 'Accessories', price: 34, stock: 23, released: '2025-10-19', tags: [] },
        { name: 'Game Controller', category: 'Electronics', price: 99, stock: 2, released: '2026-09-01', tags: ['new'] },
        { name: 'Gaming Set', category: 'Electronics', price: 299, stock: 63, released: '2025-12-24', tags: ['sale'] },
        { name: 'Yoga Mat', category: 'Fitness', price: 20, stock: 15, released: '2026-02-11', tags: ['eco'] },
        { name: 'Yoga Set', category: 'Fitness', price: 20, stock: 25, released: '2024-09-03', tags: ['sale'] }
    ];

    filter = signal<FilterBuilderExpression>({
        logic: 'and',
        filters: [
            { field: 'category', operator: 'in', value: ['Accessories', 'Fitness'] },
            {
                logic: 'or',
                filters: [
                    { field: 'price', operator: 'lt', value: 30 },
                    { field: 'tags', operator: 'in', value: ['new'] }
                ]
            }
        ]
    });

    rows = computed(() => this.items.filter(filterBuilderToPredicate(this.filter(), this.fields)));
}
```

## Text Summary

filterBuilderToText(expression, fields) writes a readable summary of the filter, for a collapsed filter bar, a saved search or a confirmation. The fields give the labels of the fields and of the options; the locale option formats the dates and numbers, and the labels option translates the words. The incomplete rules are left out, and an empty filter gives an empty string.

```typescript
import { Component, computed, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { FilterBuilderExpression, FilterBuilderField, FilterBuilderModule, filterBuilderToText } from '@exhaustive-ui/core/filterbuilder';

@Component({
    template: `
        <div class="card flex flex-col gap-4">
            <p-filter-builder [ngModel]="filter()" (ngModelChange)="filter.set($event)" [fields]="fields" ariaLabel="Ticket filter" />
            <p class="m-0 p-3 rounded-border bg-surface-100 dark:bg-surface-800">{{ summary() || 'All tickets' }}</p>
        </div>
    `,
    standalone: true,
    imports: [FormsModule, FilterBuilderModule]
})
export class FilterbuilderSummaryDemo {
    fields: FilterBuilderField[] = [
        { name: 'title', label: 'Title', type: 'text' },
        {
            name: 'priority',
            label: 'Priority',
            type: 'select',
            options: [
                { label: 'Low', value: 1 },
                { label: 'Medium', value: 2 },
                { label: 'High', value: 3 }
            ]
        },
        { name: 'created', label: 'Created', type: 'date' },
        { name: 'assigned', label: 'Assigned', type: 'boolean' }
    ];

    filter = signal<FilterBuilderExpression>({
        logic: 'and',
        filters: [
            { field: 'priority', operator: 'in', value: [2, 3] },
            {
                logic: 'or',
                filters: [
                    { field: 'assigned', operator: 'equals', value: false },
                    { field: 'created', operator: 'before', value: new Date(2026, 10, 1) }
                ]
            },
            { logic: 'and', not: true, filters: [{ field: 'title', operator: 'contains', value: 'test' }] }
        ]
    });

    summary = computed(() => filterBuilderToText(this.filter(), this.fields, { locale: 'en-US' }));
}
```

## Table Filters

filterBuilderToTableFilters(expression, fields) converts the filter to the filters of a Table, {{ '{' }} [field]: FilterMetadata[] {{ '}' }} , for a Table that filters on the server with lazy loading or keeps its own column filters. A Table joins the fields with AND and the rules of one field with a single AND or OR, so the conversion succeeds for an AND group of rules, or of sub-groups whose rules all filter the same field, and for an OR group on a single field. It returns null for anything else: a NOT, an OR across fields, the is empty , is not empty and is none of operators, multiselect fields and dates compared with between . In those cases, filter with filterBuilderToPredicate or send the expression itself to the server.

```typescript
import { Component, computed, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { FilterBuilderExpression, FilterBuilderField, FilterBuilderModule, filterBuilderToTableFilters } from '@exhaustive-ui/core/filterbuilder';

@Component({
    template: `
        <div class="card flex flex-col gap-4">
            <p-filter-builder [ngModel]="filter()" (ngModelChange)="filter.set($event)" [fields]="fields" [maxDepth]="2" ariaLabel="Customer filter" />
            <pre class="text-sm font-mono m-0 p-3 rounded-border bg-surface-100 dark:bg-surface-800 overflow-auto">{{ tableFilters() }}</pre>
        </div>
    `,
    standalone: true,
    imports: [FormsModule, FilterBuilderModule]
})
export class FilterbuilderTablefiltersDemo {
    fields: FilterBuilderField[] = [
        { name: 'name', label: 'Name', type: 'text' },
        { name: 'balance', label: 'Balance', type: 'number' },
        { name: 'date', label: 'Date', type: 'date' },
        { name: 'status', label: 'Status', type: 'select', options: ['qualified', 'unqualified', 'negotiation', 'new'] }
    ];

    filter = signal<FilterBuilderExpression>({
        logic: 'and',
        filters: [
            { field: 'name', operator: 'startsWith', value: 'J' },
            {
                logic: 'or',
                filters: [
                    { field: 'balance', operator: 'lt', value: 1000 },
                    { field: 'balance', operator: 'gt', value: 50000 }
                ]
            },
            { field: 'status', operator: 'in', value: ['qualified', 'new'] }
        ]
    });

    tableFilters = computed(() => {
        const filters = filterBuilderToTableFilters(this.filter(), this.fields);
        return filters ? JSON.stringify(filters, null, 2) : 'null: a Table cannot express this filter';
    });
}
```

## Validation

A rule is incomplete while its field, its operator or the value its operator needs is missing. Once the focus leaves an incomplete rule, the rule and its missing controls are shown as invalid, with a message linked to the rule; markAllAsTouched() or the touched input shows every incomplete rule at once. The valid() and incomplete() signals and the onChange event tell the state, and the form control gets a filterBuilder error. onlyValid emits the filter without its incomplete rules and empty groups, and only when this complete part changes: picking a field or typing in a new rule does not emit it. Use it to run a search only when the filter really changes; filterBuilderPrune gives the same result from any value.

```typescript
import { Component, signal } from '@angular/core';
import { FilterBuilderExpression, FilterBuilderField, FilterBuilderModule, filterBuilderCount } from '@exhaustive-ui/core/filterbuilder';

@Component({
    template: `
        <div class="card flex flex-col gap-4">
            <p-filter-builder [fields]="fields" ariaLabel="Product filter" (onlyValid)="onlyValid($event)" />
            <p class="m-0 text-sm" aria-live="polite">Searches run: {{ searches() }}. Rules applied: {{ applied() }}.</p>
        </div>
    `,
    standalone: true,
    imports: [FilterBuilderModule]
})
export class FilterbuilderValidationDemo {
    fields: FilterBuilderField[] = [
        { name: 'name', label: 'Name', type: 'text' },
        { name: 'price', label: 'Price', type: 'number' },
        { name: 'category', label: 'Category', type: 'select', options: ['Accessories', 'Clothing', 'Electronics', 'Fitness'] }
    ];

    searches = signal(0);

    applied = signal(0);

    onlyValid(filter: FilterBuilderExpression) {
        this.searches.update((count) => count + 1);
        this.applied.set(filterBuilderCount(filter));
    }
}
```

## Forms: Template Driven

The component adds a filterBuilder error, with the number of incomplete rules, while a rule is incomplete. Bind touched to show every incomplete rule once the form is submitted, and name the filter with ariaLabelledBy .

```typescript
import { Component, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MessageService } from '@exhaustive-ui/core/api';
import { FilterBuilderExpression, FilterBuilderField, FilterBuilderModule } from '@exhaustive-ui/core/filterbuilder';
import { ToastModule } from '@exhaustive-ui/core/toast';
import { MessageModule } from '@exhaustive-ui/core/message';
import { ButtonModule } from '@exhaustive-ui/core/button';

@Component({
    template: `
        <p-toast />
        <div class="card">
            <form #exampleForm="ngForm" (ngSubmit)="onSubmit(exampleForm)" class="flex flex-col gap-4">
                <div class="flex flex-col gap-2">
                    <span id="segment-td" class="font-medium">Segment</span>
                    <p-filter-builder #model="ngModel" [(ngModel)]="segment" name="segment" [fields]="fields" ariaLabelledBy="segment-td" [touched]="model.touched || exampleForm.submitted" />
                    @if (model.invalid && (model.touched || exampleForm.submitted)) {
                        <p-message severity="error" size="small" variant="simple">Complete or remove the incomplete rules.</p-message>
                    }
                </div>
                <button pButton severity="secondary" type="submit" class="self-start"><span pButtonLabel>Save segment</span></button>
            </form>
        </div>
    `,
    standalone: true,
    imports: [FormsModule, FilterBuilderModule, ToastModule, MessageModule, ButtonModule],
    providers: [MessageService]
})
export class FilterbuilderTemplatedrivenformsDemo {
    messageService = inject(MessageService);

    fields: FilterBuilderField[] = [
        { name: 'email', label: 'Email', type: 'text' },
        { name: 'orders', label: 'Orders', type: 'number' },
        { name: 'newsletter', label: 'Newsletter', type: 'boolean' }
    ];

    segment: FilterBuilderExpression = { logic: 'and', filters: [{ field: 'orders', operator: 'gt', value: null }] };

    onSubmit(form: any) {
        if (form.valid) {
            this.messageService.add({ severity: 'success', summary: 'Success', detail: 'Segment saved', life: 3000 });
            form.resetForm({ segment: { logic: 'and', filters: [] } });
        }
    }
}
```

## Reactive Forms

FilterBuilder can also be used with reactive forms, through the formControlName property. The filterBuilder error is added by the component itself, and the value written with setValue or reset rebuilds the tree.

```typescript
import { Component, inject } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule } from '@angular/forms';
import { MessageService } from '@exhaustive-ui/core/api';
import { FilterBuilderField, FilterBuilderModule } from '@exhaustive-ui/core/filterbuilder';
import { ToastModule } from '@exhaustive-ui/core/toast';
import { MessageModule } from '@exhaustive-ui/core/message';
import { ButtonModule } from '@exhaustive-ui/core/button';

@Component({
    template: `
        <p-toast />
        <div class="card">
            <form [formGroup]="exampleForm" (ngSubmit)="onSubmit()" class="flex flex-col gap-4">
                <div class="flex flex-col gap-2">
                    <span id="alert-rf" class="font-medium">Alert conditions</span>
                    <p-filter-builder formControlName="conditions" [fields]="fields" ariaLabelledBy="alert-rf" [touched]="isTouched()" />
                    @if (isInvalid()) {
                        <p-message severity="error" size="small" variant="simple">Complete or remove the incomplete rules.</p-message>
                    }
                </div>
                <button pButton severity="secondary" type="submit" class="self-start"><span pButtonLabel>Create alert</span></button>
            </form>
        </div>
    `,
    standalone: true,
    imports: [ReactiveFormsModule, FilterBuilderModule, ToastModule, MessageModule, ButtonModule],
    providers: [MessageService]
})
export class FilterbuilderReactiveformsDemo {
    private fb = inject(FormBuilder);

    messageService = inject(MessageService);

    fields: FilterBuilderField[] = [
        { name: 'cpu', label: 'CPU %', type: 'number' },
        { name: 'host', label: 'Host', type: 'text' },
        { name: 'region', label: 'Region', type: 'select', options: ['eu-west', 'us-east', 'ap-south'] }
    ];

    exampleForm: FormGroup;

    formSubmitted: boolean = false;

    constructor() {
        this.exampleForm = this.fb.group({
            conditions: [
                {
                    logic: 'and',
                    filters: [
                        { field: 'cpu', operator: 'gt', value: 90 },
                        { field: 'region', operator: null }
                    ]
                }
            ]
        });
    }

    onSubmit() {
        this.formSubmitted = true;
        if (this.exampleForm.valid) {
            this.messageService.add({ severity: 'success', summary: 'Success', detail: 'Alert created', life: 3000 });
            this.exampleForm.reset({ conditions: { logic: 'and', filters: [] } });
            this.formSubmitted = false;
        }
    }

    isTouched() {
        return !!this.exampleForm.get('conditions')?.touched || this.formSubmitted;
    }

    isInvalid() {
        return !!this.exampleForm.get('conditions')?.invalid && this.isTouched();
    }
}
```

## Signal Forms

FilterBuilder can also be used with Angular Signal Forms . The [formField] directive binds the component to a field of the expression type, and sets its touched state, so the incomplete rules are shown once the field is touched or the form submitted. Check the rules in the schema with filterBuilderIncomplete and filterBuilderCount in validate rules.

```typescript
import { Component, inject, signal } from '@angular/core';
import { form, FormField, submit, validate } from '@angular/forms/signals';
import { MessageService } from '@exhaustive-ui/core/api';
import { FilterBuilderExpression, FilterBuilderField, FilterBuilderModule, filterBuilderCount, filterBuilderIncomplete } from '@exhaustive-ui/core/filterbuilder';
import { ButtonModule } from '@exhaustive-ui/core/button';
import { ToastModule } from '@exhaustive-ui/core/toast';
import { MessageModule } from '@exhaustive-ui/core/message';

const FIELDS: FilterBuilderField[] = [
    { name: 'title', label: 'Title', type: 'text' },
    { name: 'year', label: 'Year', type: 'number' },
    { name: 'genre', label: 'Genre', type: 'multiselect', options: ['Drama', 'Comedy', 'Documentary', 'Animation'] }
];

@Component({
    template: `
        <p-toast />
        <div class="card">
            <form novalidate (submit)="onSubmit($event)" class="flex flex-col gap-4">
                <div class="flex flex-col gap-2">
                    <span id="search-sf" class="font-medium">Saved search</span>
                    <p-filter-builder [formField]="searchForm.filter" [fields]="fields" ariaLabelledBy="search-sf" />
                    @let filter = searchForm.filter();
                    @if (filter.invalid() && filter.touched()) {
                        <p-message severity="error" size="small" variant="simple">{{ filter.errors()[0]?.kind === 'empty' ? 'Add at least one rule.' : 'Complete or remove the incomplete rules.' }}</p-message>
                    }
                </div>
                <button pButton severity="secondary" type="submit" class="self-start"><span pButtonLabel>Save search</span></button>
            </form>
        </div>
    `,
    standalone: true,
    imports: [FormField, FilterBuilderModule, ButtonModule, ToastModule, MessageModule],
    providers: [MessageService]
})
export class FilterbuilderSignalformsDemo {
    messageService = inject(MessageService);

    fields = FIELDS;

    model = signal<{ filter: FilterBuilderExpression }>({ filter: { logic: 'and', filters: [] } });

    searchForm = form(this.model, (f) => {
        validate(f.filter, ({ value }) => (filterBuilderIncomplete(value(), FIELDS) ? { kind: 'incomplete' } : filterBuilderCount(value(), FIELDS) === 0 ? { kind: 'empty' } : null));
    });

    onSubmit(event: Event) {
        event.preventDefault();
        submit(this.searchForm, async () => {
            this.messageService.add({ severity: 'success', summary: 'Success', detail: 'Search saved', life: 3000 });
            this.searchForm().reset({ filter: { logic: 'and', filters: [] } });
        });
    }
}
```

## Accessibility

Screen Reader Every group is an element with the group role named by its number, such as Group 1 or Group 1.2 for the second sub-group of the root group; name the root group with ariaLabel or ariaLabelledBy . Its items are a list, and every rule is also a group , named Rule 2 in group 1 . Each control of a rule says which rule it belongs to: Field for rule 2 in group 1 , Operator for rule 2 in group 1 , Value for rule 2 in group 1 , and Start value and End value for the two editors of between . The icon buttons are named in the same way, Duplicate rule 2 in group 1 and Remove group 1.1 , and the buttons with a text, Add rule and Add group , keep their text at the start of their name. The logic of a group is a SelectButton named Logic of group 1 , whose buttons are pressed or not, and NOT is a toggle button with aria-pressed . The AND and OR words shown between the items repeat the logic and are hidden from screen readers. Adding, duplicating and removing a rule or a group is announced by a polite live region, such as Rule 3 added to group 1 . The focus then moves to the field of the new rule, or after a removal to the next item, the previous one, or the Add rule button of the group when it is empty, so it is never lost. An incomplete rule that the focus left gets aria-invalid on its missing controls and a message linked with aria-describedby . Every text can be replaced, or translated, with the labels input, where {{ '{' }}0{{ '}' }} and {{ '{' }}1{{ '}' }} are the numbers of the rule and of the group.

## Filter Builder

FilterBuilder builds a filter as a tree of conditions: groups joined by AND or OR, optionally negated, holding rules (a field, an operator and a value) and sub-groups.
Each field type has its operators and its value editor, the value is a serializable expression, and  `filterBuilderToPredicate`  filters an array in memory.

### Props

| Name | Type | Default | Description |
|------|------|---------|-------------|
| dt | Object | undefined | Defines scoped design tokens of the component. |
| unstyled | boolean | undefined | Indicates whether the component should be rendered without styles. |
| pt | FilterBuilderPassThrough | undefined | Used to pass attributes to DOM elements inside the component. |
| ptOptions | PassThroughOptions | undefined | Used to configure passthrough(pt) options of the component. |
| required | boolean | false | There must be a value (if set). |
| invalid | boolean | false | When present, it specifies that the component should have invalid state style. |
| touched | boolean | undefined | Whether the field has been touched. Signal Forms sets it through  `[formField]` : the invalid style and  `aria-invalid`  then wait until the field is touched, or the form is submitted, like the error messages. Left unset,  `invalid`  applies at once. |
| $invalid | Signal<boolean> | - | The invalid state shown by the component:  `invalid` , once the field is touched when  `touched`  is set; undefined when  `invalid`  is unset. |
| disabled | boolean | false | When present, it specifies that the component should have disabled state style. |
| name | string | undefined | When present, it specifies that the name of the input. |
| fluid | boolean | false | Spans 100% width of the container when enabled. |
| variant | "filled" \| "outlined" | 'outlined' | Specifies the input variant of the component. |
| size | "small" \| "large" | undefined | Specifies the size of the component. |
| inputSize | number | undefined | Specifies the visible width of the input element in characters. |
| pattern | string | undefined | Specifies the value must match the pattern. |
| min | number | undefined | The value must be greater than or equal to the value. |
| max | number | undefined | The value must be less than or equal to the value. |
| step | number | undefined | Unless the step is set to the any literal, the value must be min + an integral multiple of the step. |
| minlength | number | undefined | The number of characters (code points) must not be less than the value of the attribute, if non-empty. |
| maxlength | number | undefined | The number of characters (code points) must not exceed the value of the attribute. |
| fields | FilterBuilderField[] | [] | Fields the rules can filter on, with their label, type, options and operators. |
| operators | Partial<Record<FilterBuilderFieldType, FilterBuilderOperator[]>> | - | Operators of each field type, replacing the defaults; the operators of a field take precedence. |
| maxDepth | number | 3 | Maximum depth of the groups, the root group being at depth 1: 1 allows no sub-group. |
| showNot | boolean | true | Whether the groups have a NOT toggle that negates them. |
| defaultLogic | FilterBuilderLogic | 'and' | Logic of the new groups. |
| dateFormat | string | - | Format of the dates in the DatePicker, such as  `dd/mm/yy` ; the locale format when not set. |
| appendTo | any | - | Target element to attach the overlays of the Selects and DatePickers to,  `'body'`  or  `'self'` . |
| ariaLabel | string | - | Accessible name of the root group; the groupLabel text when not set. |
| ariaLabelledBy | string | - | Identifier of the element that labels the root group. |
| labels | Partial<FilterBuilderLabels> | - | Texts of the component, merged with the English defaults. |
| value | Signal<FilterBuilderGroup> | computed<FilterBuilderExpression>(() => this.toExpression(this.root()) as FilterBuilderExpression) | The value: the expression built, without the keys of the rendering. |
| incomplete | Signal<number> | computed(() => filterBuilderIncomplete(this.value(), this.fields())) | Number of incomplete rules. |
| valid | Signal<boolean> | computed(() => this.incomplete() === 0) | Whether every rule is complete. |

### Emits

| Name | Parameters | Description |
|------|------------|-------------|
| onChange | event: FilterBuilderChangeEvent | Callback to invoke when the expression changes. |
| onlyValid | value: FilterBuilderGroup | Callback to invoke when the complete part of the expression changes: the expression without its incomplete rules and empty groups, ready to apply. A rule being typed or a field picked without a value does not emit it. |
| onFocus | event: FocusEvent | Callback to invoke when the component receives the focus. |
| onBlur | event: FocusEvent | Callback to invoke when the component loses the focus. |

### Methods

| Name | Parameters | Return Type | Description |
|------|------------|-------------|-------------|
| addRule | groupId: string | void | Adds an empty rule at the end of a group, the root group by default, and moves the focus to its field. |
| addGroup | groupId: string | void | Adds a sub-group with an empty rule at the end of a group, the root group by default, when the maximum depth allows it. |
| duplicate | ruleId: string | void | Adds a copy of a rule just after it. |
| remove | id: string | void | Removes a rule or a sub-group, and moves the focus to the next item, the previous one or the add rule button of the group. |
| clear |  | void | Removes every rule and group. |
| markAllAsTouched |  | void | Shows the missing parts of every incomplete rule, as when the form is submitted. |
| focus |  | void | Moves the focus to the first control of the component. |

## Pass Through Options

| Name | Type | Description |
|------|------|-------------|
| host | PassThroughOption<HTMLElement, I> | Used to pass attributes to the host's DOM element. |
| root | PassThroughOption<HTMLElement, I> | Used to pass attributes to the root's DOM element. |
| group | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to the element of each group. |
| groupHeader | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to the header of each group. |
| notButton | PassThroughOption<HTMLButtonElement, I> | Used to pass attributes to the NOT toggle of each group. |
| pcLogic | SelectButtonPassThrough | Used to pass attributes to the SelectButton of the logic operator of each group. |
| groupContent | PassThroughOption<HTMLUListElement, I> | Used to pass attributes to the list of the rules and sub-groups of each group. |
| item | PassThroughOption<HTMLLIElement, I> | Used to pass attributes to each item of a group, a rule or a sub-group. |
| connector | PassThroughOption<HTMLSpanElement, I> | Used to pass attributes to the AND / OR label shown before the second and next items of a group. |
| rule | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to each rule. |
| pcField | SelectPassThrough | Used to pass attributes to the Select of the field of each rule. |
| pcOperator | SelectPassThrough | Used to pass attributes to the Select of the operator of each rule. |
| value | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to the element around the value editors of each rule. |
| pcInputText | InputTextPassThrough | Used to pass attributes to the InputText of the text values. |
| pcInputNumber | InputNumberPassThrough | Used to pass attributes to the InputNumber of the number values. |
| pcDatePicker | DatePickerPassThrough | Used to pass attributes to the DatePicker of the date values. |
| pcSelect | SelectPassThrough | Used to pass attributes to the Select of the single choice values. |
| pcMultiSelect | MultiSelectPassThrough | Used to pass attributes to the MultiSelect of the list values. |
| pcToggleSwitch | ToggleSwitchPassThrough | Used to pass attributes to the ToggleSwitch of the boolean values. |
| rangeSeparator | PassThroughOption<HTMLSpanElement, I> | Used to pass attributes to the word between the two editors of a between operator. |
| ruleMessage | PassThroughOption<HTMLSpanElement, I> | Used to pass attributes to the message of an incomplete rule. |
| actionButton | ButtonPassThrough | Used to pass attributes to the action buttons: add rule, add group, duplicate and remove. |
| emptyMessage | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to the message shown while the root group is empty. |
| liveRegion | PassThroughOption<HTMLSpanElement, I> | Used to pass attributes to the live region of the announcements. |

## Theming

### CSS Classes

| Class | Description |
|-------|-------------|
| p-filterbuilder | Class name of the root element |
| p-filterbuilder-group | Class name of a group |
| p-filterbuilder-group-header | Class name of the header of a group |
| p-filterbuilder-not-button | Class name of the NOT toggle of a group |
| p-filterbuilder-logic | Class name of the logic SelectButton of a group |
| p-filterbuilder-group-actions | Class name of the actions of a group |
| p-filterbuilder-group-content | Class name of the list of the items of a group |
| p-filterbuilder-item | Class name of an item of a group |
| p-filterbuilder-connector | Class name of the AND / OR label between the items of a group |
| p-filterbuilder-rule | Class name of a rule |
| p-filterbuilder-field | Class name of the field Select of a rule |
| p-filterbuilder-operator | Class name of the operator Select of a rule |
| p-filterbuilder-value | Class name of the value editors of a rule |
| p-filterbuilder-editor | Class name of a value editor |
| p-filterbuilder-switch | Class name of the ToggleSwitch of a boolean value and its text |
| p-filterbuilder-range-separator | Class name of the word between the two editors of a between operator |
| p-filterbuilder-rule-actions | Class name of the actions of a rule |
| p-filterbuilder-action-button | Class name of an action button |
| p-filterbuilder-rule-message | Class name of the message of an incomplete rule |
| p-filterbuilder-empty-message | Class name of the message of the empty root group |

### Design Tokens

| Token | CSS Variable | Description |
|-------|--------------|-------------|
| filterbuilder.root.color | --p-filterbuilder-root-color | Text color of root |
| filterbuilder.group.background | --p-filterbuilder-group-background | Background of the root group |
| filterbuilder.group.nested.background | --p-filterbuilder-group-nested-background | Background of a nested group |
| filterbuilder.group.border.color | --p-filterbuilder-group-border-color | Border color of group |
| filterbuilder.group.border.radius | --p-filterbuilder-group-border-radius | Border radius of group |
| filterbuilder.group.padding | --p-filterbuilder-group-padding | Padding of group |
| filterbuilder.group.gap | --p-filterbuilder-group-gap | Gap between the items of group |
| filterbuilder.group.negated.border.color | --p-filterbuilder-group-negated-border-color | Border color of the start edge of a negated group |
| filterbuilder.group.header.gap | --p-filterbuilder-group-header-gap | Gap of group header |
| filterbuilder.connector.gap | --p-filterbuilder-connector-gap | Gap between the connector and its item |
| filterbuilder.connector.font.size | --p-filterbuilder-connector-font-size | Font size of connector |
| filterbuilder.connector.font.weight | --p-filterbuilder-connector-font-weight | Font weight of connector |
| filterbuilder.connector.color | --p-filterbuilder-connector-color | Color of connector |
| filterbuilder.rule.background | --p-filterbuilder-rule-background | Background of rule |
| filterbuilder.rule.border.color | --p-filterbuilder-rule-border-color | Border color of rule |
| filterbuilder.rule.border.radius | --p-filterbuilder-rule-border-radius | Border radius of rule |
| filterbuilder.rule.padding | --p-filterbuilder-rule-padding | Padding of rule |
| filterbuilder.rule.gap | --p-filterbuilder-rule-gap | Gap of rule |
| filterbuilder.rule.invalid.border.color | --p-filterbuilder-rule-invalid-border-color | Border color of an incomplete rule |
| filterbuilder.rule.message.font.size | --p-filterbuilder-rule-message-font-size | Font size of rule message |
| filterbuilder.rule.message.color | --p-filterbuilder-rule-message-color | Color of rule message |
| filterbuilder.empty.message.padding | --p-filterbuilder-empty-message-padding | Padding of empty message |
| filterbuilder.empty.message.color | --p-filterbuilder-empty-message-color | Color of empty message |

