# Angular TreeList Filter Row

The [Angular TreeList](https://www.telerik.com/kendo-angular-ui-develop/components/treelist) enables you to embed a filter row above the column headers. To add a filter row to the TreeList, set the [`filterable`](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/api/treelistcomponent#filterable) option to `true`

The following example demonstrates the default filter row of the TreeList.

[Demo Source](https://demos.telerik.com/kendo-angular-ui/demos/treelist/filtering/row/basic/source.txt)

## Built-in Filter-Row Components

To change the default appearance of the filtering UI, use the [`FilterCellTemplateDirective`](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/api/filtercelltemplatedirective).

The TreeList package exposes the default filter-row UI for the basic data types as ready-to-use components. These components are especially useful when you need to customize the filter operators.

The following ready-to-use components are available to use inside the `FilterCellTemplateDirective`:

* [`kendo-treelist-boolean-filter-cell`](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/api/booleanfiltercellcomponent)
* [`kendo-treelist-date-filter-cell`](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/api/datefiltercellcomponent)
* [`kendo-treelist-numeric-filter-cell`](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/api/numericfiltercellcomponent)
* [`kendo-treelist-string-filter-cell`](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/api/stringfiltercellcomponent)

All built-in filter row components require you to bind the `column` and `filter` attributes to the template context.

```html
<kendo-treelist-column filter="text" field="name" title="Name" [width]="180">
    <ng-template kendoTreeListFilterCellTemplate let-filter let-column="column">
        <kendo-treelist-string-filter-cell [column]="column" [filter]="filter">
        </kendo-treelist-string-filter-cell>
    </ng-template>
</kendo-treelist-column>
```

The built-in filter row components enable you to utilize the available configuration options and customize the filter settings of the TreeList.

### Default Filter Operator

The default operators for the built-in filter row components are:

| Component                            | Default Operator |
| ------------------------------------ | ---------------- |
| `kendo-treelist-boolean-filter-cell` | `"eq"`           |
| `kendo-treelist-date-filter-cell`    | `"gte"`          |
| `kendo-treelist-numeric-filter-cell` | `"eq"`           |
| `kendo-treelist-string-filter-cell`  | `"contains"`     |

> If the `operator` is set to `""`, the TreeList will use the first operator from the defined list of operators as its default operator.

You can override the default filter operators by setting the `operator` property of the built-in filter row components.

```html
<kendo-treelist-column filter="text" field="name" title="Name" [width]="180">
    <ng-template kendoTreeListFilterCellTemplate let-filter let-column="column">
        <kendo-treelist-string-filter-cell [column]="column" [filter]="filter" operator="startswith">
            <kendo-treelist-filter-startswith-operator></kendo-treelist-filter-startswith-operator>
            <kendo-treelist-filter-eq-operator></kendo-treelist-filter-eq-operator>
        </kendo-treelist-string-filter-cell>
    </ng-template>
</kendo-treelist-column>
```

The following example demonstrates how to configure a string filter with a default `startswith` operator.

[Demo Source](https://demos.telerik.com/kendo-angular-ui/demos/treelist/filtering/row/default-operator/source.txt)

### Order of Filter Operators

You can manually fine-tune the order and number of available operators by adding operator components.

```html
<kendo-treelist-column filter="text" field="name" title="Name" [width]="180">
    <ng-template kendoTreeListFilterCellTemplate let-filter let-column="column">
        <kendo-treelist-string-filter-cell [column]="column" [filter]="filter">
            <kendo-treelist-filter-eq-operator></kendo-treelist-filter-eq-operator>
            <kendo-treelist-filter-contains-operator></kendo-treelist-filter-contains-operator>
        </kendo-treelist-string-filter-cell>
    </ng-template>
</kendo-treelist-column>
```

The following example demonstrates how to set the order of the operators.

[Demo Source](https://demos.telerik.com/kendo-angular-ui/demos/treelist/filtering/row/operators-order/source.txt)

### Hiding Filter Operators

To hide the list of filter operators, set the [`showOperators`](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/api/stringfiltercellcomponent#showoperators) option to `false`.

```html
<kendo-treelist-column filter="text" field="name" title="Name" [width]="180">
    <ng-template kendoTreeListFilterCellTemplate let-filter let-column="column" >
        <kendo-treelist-string-filter-cell
          [column]="column"
          [filter]="filter"
          [showOperators]="false"
        >
        </kendo-treelist-string-filter-cell>
    </ng-template>
</kendo-treelist-column>
```

The following example demonstrates how to hide the filter operators.

[Demo Source](https://demos.telerik.com/kendo-angular-ui/demos/treelist/filtering/row/hiding-operators/source.txt)

### Using Standalone Filter Operators Component

If you want to use the built-in filter operators along with any [custom input control](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/filtering/filter-row#custom-filters), define the [`FilterCellOperatorsComponent`](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/api/filtercelloperatorscomponent) inside the `kendoTreeListFilterCellTemplate` directive.

To benefit from the built-in accessibility features of the TreeList, pass the `column` context, provided by the template, to the [`column`](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/api/filtercelloperatorscomponent#column) property of the filter operators component.

```html
<ng-template kendoTreeListFilterCellTemplate let-filter let-column="column" >
    <kendo-textbox></kendo-textbox>
    <kendo-treelist-filter-cell-operators
      [column]="column"
      [operators]="[{text: 'Equals', value: 'eq'}]">
    </kendo-treelist-filter-cell-operators>
</ng-template>
```

The following example demonstrates the standalone filter operators component in action.

[Demo Source](https://demos.telerik.com/kendo-angular-ui/demos/treelist/filtering/row/custom-operators/source.txt)

## Custom Filters

The [`FilterCellTemplateDirective`](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/api/filtercelltemplatedirective) allows you to provide any custom content as a filtering UI. This feature is especially useful for scenarios in which the configuration options of the [built-in filter row components](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/filtering/filter-row#built-in-filter-row-components) aren't sufficient to achieve the desired result.

The following step-by-step guide demonstrates how to implement a custom  Boolean filter.

1. Add a template tag with the `kendoTreeListFilterCellTemplate` directive for the Boolean column and place a [MaskedTextBox component](https://www.telerik.com/kendo-angular-ui-develop/components/inputs/maskedtextbox) inside it.

   ```html
   <kendo-treelist-column field="phone" title="Phone" [width]="180">
       <ng-template kendoTreeListFilterCellTemplate>
           <kendo-maskedtextbox mask="(999) 000-0000"
             [promptPlaceholder]="prompt" [includeLiterals]="true"
             (valueChange)="phoneChange($event)"
           >
           </kendo-maskedtextbox>
       </ng-template>
   </kendo-treelist-column>
   ```

2. Handle the MaskedTextBox `valueChange` event and set the filter. Then call the `filterChange` method to notify the TreeList that the filter has been modified.

   ```ts
   public phoneChange(value: string): void {
       // Preserve unrelated filters while rebuilding the root descriptor.
       const root = { logic: 'and', filters: [], ...this.filter };
       if (!value || value.indexOf(this.prompt) >= 0) {
           removeFiltersForField(root)
       } else {
           const [ filter ] = flatten(root).filter(x => x.field === 'phone');

           if (!filter) {
               root.filters.push({
                   field: 'phone',
                   operator: 'eq',
                   value: value
               });
           } else {
               filter.value = value;
           }
       }
       this.filter = root;
   }
   ```

The following example demonstrates the full implementation of the approach.

[Demo Source](https://demos.telerik.com/kendo-angular-ui/demos/treelist/filtering/masked-filter/source.txt)

## Custom Filter Row Components

You can also create custom filtering components and use them within the [`FilterCellTemplateDirective`](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/api/filtercelltemplatedirective). This scenario is suitable when you want to reuse the custom filtering UI across multiple TreeList columns or many TreeList components.

To implement a custom reusable filter row component in the TreeList:

1. Extend the base filter cell component from the [BaseFilterCellComponent](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/api/basefiltercellcomponent) class to utilize the existing functions.

   ```ts
   export class MyCustomFilterComponent extends BaseFilterCellComponent {
       // ...
   }
   ```

2. Inject the [`FilterService`](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/api/filterservice) through the constructor and pass it to the `super` call, as it is required by the `BaseFilterCellComponent` class. This service is responsible for the communication with the host TreeList component.

   ```ts
   constructor(filterService: FilterService) {
       super(filterService);
   }
   ```

3. Modify the root filter descriptor from within the custom filter-row component by using the `applyFilter()`, `removeFilter()`, and `updateFilter()` methods provided by the `BaseFilterCellComponent`. Their purpose is to update the root filter and to remove or override the child filter for the given field.

### Using DropDownList

You can use the Kendo UI for Angular [DropDownList](https://www.telerik.com/kendo-angular-ui-develop/components/dropdowns/dropdownlist) in the TreeList and filter the data by choosing a single predefined value from a list.

[Demo Source](https://demos.telerik.com/kendo-angular-ui/demos/treelist/filtering/dropdownlist-filter/source.txt)

To integrate the DropDownList component:

1. Extend the `BaseFilterCellComponent` and pass a `FilterService` through the constructor.

   ```ts
   export class DropDownListFilterComponent extends BaseFilterCellComponent {
       constructor(filterService: FilterService) {
           super(filterService);
       }
   }
   ```

2. Add the root `CompositeFilterDescriptor` as required by the component so you can add or modify it with the filter descriptor that will be built.

   ```ts
   @Input() public filter: CompositeFilterDescriptor;
   ```

3. Provide the appropriate `textField`, `valueField`, and `data` input properties to reuse the filter component on different column fields. Pass the properties to the DropDownList component.

   ```ts
   @Input() public data: any[];
   @Input() public textField: string;
   @Input() public valueField: string;
   ```

4. (Optional) Construct a default placeholder item that will be used when the user wants to remove the filter.

   ```ts
   public get defaultItem(): any {
       return {
           [this.textField]: "Select item...",
           [this.valueField]: null
       };
   }
   ```

5. Add the DropDownList component to the template.

   ```ts
   @Component({
       selector: 'my-dropdown-filter',
       template: `
           <kendo-dropdownlist
               [data]="data"
               (valueChange)="onChange($event)"
               [defaultItem]="defaultItem"
               [value]="selectedValue"
               [valuePrimitive]="true"
               [textField]="textField"
               [valueField]="valueField">
           </kendo-dropdownlist>
       `
   })
   export class DropDownListFilterComponent extends BaseFilterCellComponent {
       // ...
   }
   ```

6. Hook the `valueChange` event handler and modify the root filter descriptor by using the `applyFilter()`, `removeFilter()`, and `updateFilter()` functions inherited from the base class.

   ```ts
   public onChange(value: any): void {
       this.applyFilter(
           value === null ? // if value of the default item
               this.removeFilter(this.valueField) : // remove the filter
               this.updateFilter({ // otherwise add/modify the filter for the field with the value
                   field: this.valueField,
                   operator: "eq",
                   value: value
               })
       ); // and update the root filter
   }
   ```

7. Place the custom filter component in the filter cell template and hook it with the respective host component fields.

   ```html
   <kendo-treelist-column field="title" title="Title" [width]="180">
       <ng-template kendoTreeListFilterCellTemplate let-filter>
           <my-dropdown-filter
             [filter]="filter"
             [data]="titles"
             field="title"
             textField="text"
             valueField="value"
           >
           </my-dropdown-filter>
       </ng-template>
   </kendo-treelist-column>
   ```

### Using MultiSelect

You can use the Kendo UI for Angular [MultiSelect](https://www.telerik.com/kendo-angular-ui-develop/components/dropdowns/multiselect) in the TreeList filter row to filter data by selecting multiple predefined values at once. The TreeList displays only rows that match any of the selected values.

[Demo Source](https://demos.telerik.com/kendo-angular-ui/demos/treelist/filtering/multiselect-filter-row/source.txt)

To integrate the MultiSelect component:

1. Extend the [`BaseFilterCellComponent`](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/api/basefiltercellcomponent) and pass a [`FilterService`](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/api/filterservice) through the constructor.

   ```ts
   export class MultiSelectFilterComponent extends BaseFilterCellComponent {
       constructor(filterService: FilterService) {
           super(filterService);
       }
   }
   ```

2. Add the root [`CompositeFilterDescriptor`](https://www.telerik.com/kendo-angular-ui-develop/components/data-query/api/compositefilterdescriptor), the list of available `data` items, and the target `field` name as required inputs.

   ```ts
   @Input() public filter: CompositeFilterDescriptor;
   @Input() public data: string[];
   @Input() public field: string;
   ```

3. Compute the currently selected values from the root filter by flattening the composite descriptors and returning only those that match the target field.

   ```ts
   const flatten = (filter: CompositeFilterDescriptor): FilterDescriptor[] => {
       const filters = (filter || {}).filters;
       if (!filters) {
           return [];
       }
       // Flatten nested descriptors so selections can be restored for this field.
       return filters.reduce(
           (result: FilterDescriptor[], current) =>
               result.concat(isCompositeFilterDescriptor(current) ? flatten(current) : [current as FilterDescriptor]),
           []
       );
   };

   public get currentValue(): string[] {
       return flatten(this.filter)
           .filter((f: FilterDescriptor) => f.field === this.field)
           .map((f: FilterDescriptor) => f.value);
   }
   ```

4. Add the MultiSelect component to the template.

   ```ts
   @Component({
       selector: 'my-multiselect-filter',
       template: `
           <kendo-multiselect
               [data]="data"
               [value]="currentValue"
               [valuePrimitive]="true"
               (valueChange)="onChange($event)"
           >
           </kendo-multiselect>
       `
   })
   export class MultiSelectFilterComponent extends BaseFilterCellComponent {
       // ...
   }
   ```

5. Handle the [`valueChange`](https://www.telerik.com/kendo-angular-ui-develop/components/dropdowns/api/multiselectcomponent#valuechange) event of the MultiSelect. Remove any existing filter for the field, then push a new composite filter with `"or"` logic when values are selected, or apply the cleaned root filter when the selection is cleared.

   ```ts
   public onChange(values: string[]): void {
       const root = this.removeFilter(this.field) ?? { logic: 'and', filters: [] };
       if (values.length > 0) {
           root.filters.push({
               // OR lets rows match any selected value.
               logic: 'or',
               filters: values.map((value) => ({
                   field: this.field,
                   operator: 'eq',
                   value,
               })),
           });
       }
       this.applyFilter(root);
   }
   ```

6. Place the custom filter component in the filter cell template and provide the list of filterable values.

   ```html
   <kendo-treelist-column field="title" title="Title">
       <ng-template kendoTreeListFilterCellTemplate let-filter>
           <my-multiselect-filter
               [filter]="filter"
               [data]="titles"
               field="title"
           >
           </my-multiselect-filter>
       </ng-template>
   </kendo-treelist-column>
   ```

### Using DateRange

The [Angular TreeList](https://www.telerik.com/kendo-angular-ui-develop/components/treelist) enables you to implement custom filtering which is based on a given period between two dates.

[Demo Source](https://demos.telerik.com/kendo-angular-ui/demos/treelist/filtering/date-range-cell/source.txt)

To create a custom DateRange filter in the TreeList:

1. Extend the `BaseFilterCellComponent` and pass a `FilterService` through the constructor.

   ```ts
   export class DateRangeFilterCellComponent extends BaseFilterCellComponent {
       constructor(filterService: FilterService) {
           super(filterService);
       }
   }
   ```

2. Add the root `CompositeFilterDescriptor` as required by the component so you can add or modify it with the filter descriptor that will be built.

   ```ts
   @Input() public filter: CompositeFilterDescriptor;
   ```

3. Add the [DateRange](https://www.telerik.com/kendo-angular-ui-develop/components/dateinputs/daterange) component to the custom `DateRangeFilterCellComponent` template and handle the `valueChange` events of the respective `DateInput` components.

   ```html
   <kendo-daterange>
       <kendo-dateinput
       kendoDateRangeStartInput
           [value]="start"
           (valueChange)="filterRange($event, end)">
       </kendo-dateinput>
       -
       <kendo-dateinput
           kendoDateRangeEndInput
           [value]="end"
           (valueChange)="filterRange(start, $event)">
       </kendo-dateinput>
   </kendo-daterange>
   ```

4. Construct a `CompositeFilterDescriptor` which describes the selected date range and add it to the root filter of the TreeList. Use the `filterService` to update the `CompositeFilterDescriptor` applied to the TreeList.

   ```ts
   public filterRange(start: Date, end: Date): void {
       // Remove the previous range so each date change replaces it.
       this.filter = this.removeFilter(this.field);

       const filters = [];

       if (start) {
           filters.push({
               field: this.field,
               operator: "gte",
               value: start
           });
       }

       if (end) {
           filters.push({
               field: this.field,
               operator: "lte",
               value: end
           });
       }

       const root = this.filter || {
           logic: "and",
           filters: []
       };

       if (filters.length) {
           root.filters.push(...filters);
       }

       this.filterService.filter(root);
   }
   ```

## Suggested Links

* [FilterDescriptors](https://www.telerik.com/kendo-angular-ui-develop/components/data-query/api/filterdescriptor)
* [dataStateChange](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/api/treelistcomponent#datastatechange)
* [Built-In Row Filter Templates](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/filtering/filter-row)
* [Built-In Menu Filter Templates](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/filtering/filter-menu)
* [Reusable Custom Filter Components](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/filtering/filter-row#custom-filter-row-components)
* [API Reference of the TreeListComponent](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/api/treelistcomponent)
* [Data Binding Basics](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/data-binding/basics)
* [Automatic Data Binding](https://www.telerik.com/kendo-angular-ui-develop/components/treelist/data-binding/local-data#automatic-data-processing)
