Angular Query Builder 구성 요소 개요
Angular Query Builder는 Angular Components의 일부이며 개발자가 지정된 데이터 세트에 대한 복잡한 데이터 필터링 쿼리를 빌드할 수 있는 풍부한 UI를 제공합니다. 이 구성 요소를 사용하면 표현식 트리를 빌드하고 각 필드의 데이터 유형에 따라 결정되는 편집기와 조건 목록을 사용하여 표현식 트리 간에 AND/OR 조건을 설정할 수 있습니다. 그런 다음 표현식 트리를 백엔드가 지원하는 형식의 쿼리로 쉽게 변환할 수 있습니다.
The IgxQueryBuilderComponent component provides a way to build complex queries through the UI. By specifying AND/OR operators, conditions and values the user creates an expression tree which describes the query.
Angular Query Builder Example
Angular Query Builder 구성 요소의 기본 기능을 보여주기 위해 이 Angular Query Builder 예제를 만들었습니다. 더하기 버튼을 클릭하여 조건, "and" 그룹 및 "or" 그룹을 추가합니다. 표현식을 그룹화하거나 그룹을 해제하고 순서를 변경하는 것은 Drag&Drop 기능을 통해 수행할 수 있습니다.
Getting Started with Ignite UI for Angular Query Builder
Ignite UI for Angular Query Builder 구성 요소를 시작하려면 먼저 Ignite UI for Angular 설치해야 합니다. 기존 Angular 애플리케이션에서 다음 명령을 입력합니다.
ng add igniteui-angular
Ignite UI for Angular에 대한 전체 소개는 시작 항목을 참조하십시오.
다음 단계는 다음 단계를 가져오는 것입니다.IgxQueryBuilderModule 안에 app.module.ts 파일.
// app.module.ts
import { IgxQueryBuilderModule } from 'igniteui-angular';
// import { IgxQueryBuilderModule } from '@infragistics/igniteui-angular'; for licensed package
@NgModule({
...
imports: [..., IgxQueryBuilderModule],
...
})
export class AppModule {}
또는16.0.0 독립 실행형 의존성으로 가져오IgxQueryBuilderComponent 거나, 토큰을IGX_QUERY_BUILDER_DIRECTIVES 사용해 컴포넌트와 그 지원 컴포넌트, 명령어를 가져올 수도 있습니다.
// home.component.ts
import { IGX_QUERY_BUILDER_DIRECTIVES, FilteringExpressionsTree, FieldType } from 'igniteui-angular';
// import { IGX_QUERY_BUILDER_DIRECTIVES, FilteringExpressionsTree, FieldType } from '@infragistics/igniteui-angular'; for licensed package
@Component({
selector: 'app-home',
template: `
<igx-query-builder #queryBuilder
[entities]="entities"
[(expressionTree)]="expressionTree"
(expressionTreeChange)="onExpressionTreeChange()">
</igx-query-builder>
`,
styleUrls: ['home.component.scss'],
standalone: true,
imports: [IGX_QUERY_BUILDER_DIRECTIVES]
/* or imports: [IgxQueryBuilderComponent] */
})
export class HomeComponent {
public expressionTree: FilteringExpressionsTree;
public entities: Array<any>;
public onExpressionTreeChange() {
...
}
}
Now that you have the Ignite UI for Angular Query Builder module or directives imported, you can start using the igx-query-builder component.
Using the Angular Query Builder
처음에 표현식 트리가 설정되지 않은 경우 먼저 엔터티와 쿼리가 반환해야 하는 필드를 선택합니다. 그런 다음 조건 또는 하위 그룹을 추가할 수 있습니다.
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. When selecting a new entity a confirmation dialog will be shown, unless the showEntityChangeDialog input property is set to false.
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 input property. You could use it to set an initial state of the control and access the user-specified filtering logic.
ngAfterViewInit(): void {
const innerTree = new FilteringExpressionsTree(FilteringLogic.And, undefined, 'Companies', ['ID']);
innerTree.filteringOperands.push({
fieldName: 'Employees',
condition: IgxNumberFilteringOperand.instance().condition('greaterThan'),
conditionName: 'greaterThan',
searchVal: 100
});
innerTree.filteringOperands.push({
fieldName: 'Contact',
condition: IgxBooleanFilteringOperand.instance().condition('true'),
conditionName: 'true'
});
const tree = new FilteringExpressionsTree(FilteringLogic.And, undefined, 'Orders', ['*']);
tree.filteringOperands.push({
fieldName: 'CompanyID',
condition: IgxStringFilteringOperand.instance().condition('inQuery'),
conditionName: 'inQuery',
searchTree: innerTree
});
tree.filteringOperands.push({
fieldName: 'OrderDate',
condition: IgxDateFilteringOperand.instance().condition('before'),
conditionName: 'before',
searchVal: new Date('2024-01-01T00:00:00.000Z')
});
tree.filteringOperands.push({
fieldName: 'ShippedDate',
condition: IgxDateFilteringOperand.instance().condition('null'),
conditionName: 'null'
});
this.queryBuilder.expressionTree = tree;
}
The expressionTree is a two-way bindable property which means a corresponding expressionTreeChange output is implemented that emits when the end-user changes the UI by creating, editing or removing conditions. It can also be subscribed separately to receive notifications and react to such changes.
<igx-query-builder #queryBuilder
[entities]="entities"
[(expressionTree)]="expressionTree"
(expressionTreeChange)="onExpressionTreeChange()">
</igx-query-builder>
Expressions Dragging
컨디션 칩은 마우스 드래그 앤 드롭 또는 키보드 재정렬 방식을 사용하여 쉽게 재배치할 수 있습니다. 이를 통해 사용자는 쿼리 논리를 동적으로 조정할 수 있습니다.
- 칩을 드래그하면 상태/내용이 수정되지 않고 위치만 수정됩니다.
- 칩은 그룹 및 하위 그룹을 따라 드래그할 수도 있습니다. 예를 들어, 표현식 그룹화/그룹 해제는 Expressions Dragging 기능을 통해 수행됩니다. 이미 존재하는 조건을 그룹화하려면 먼저 '추가' 그룹 버튼을 통해 새 그룹을 추가해야 합니다. 그런 다음 드래그를 통해 필요한 표현식을 해당 그룹으로 이동할 수 있습니다. 그룹을 해제하려면 모든 조건을 현재 그룹 외부로 드래그하고 마지막 조건이 이동하면 그룹이 삭제됩니다.
Note
한 쿼리 트리의 칩은 다른 쿼리 트리에서 드래그 할 수 없습니다 (예 : 부모에서 내부로 또는 그 반대로).
Keyboard interaction
주요 조합
- Tab / Shift + Tab- 다음/이전 칩으로 이동하고, 표시기를 드래그하고, 버튼을 제거하고, '추가' 표현식 버튼을 클릭합니다.
- Arrow Down / Arrow Up- 칩의 드래그 인디케이터에 초점이 맞춰지면 칩을 위/아래로 움직일 수 있습니다.
- Space / Enter- 초점이 맞춰진 표현식이 편집 모드로 들어갑니다. 칩이 이동되면 새 위치를 확인합니다.
- Esc- 칩의 재정렬이 취소되고 원래 위치로 돌아갑니다.
Note
키보드 재정렬은 마우스 드래그 앤 드롭과 동일한 기능을 제공합니다. 칩이 이동되면 사용자는 새 위치를 확인하거나 재주문을 취소해야 합니다.
Templating
Ignite UI for Angular Query Builder 구성 요소를 사용하면 다음과 같은 미리 정의된 참조 이름을 사용하여 구성 요소의 헤더 및 검색 값에 대한 템플릿을 정의할 수 있습니다.
헤더 템플릿
By default the IgxQueryBuilderComponent header would not be displayed. In order to define such, the IgxQueryBuilderHeaderComponent should be added inside of the igx-query-builder.
Then, for setting the header title could be used the title input and passing content inside of the igx-query-builder-header allows templating the query builder header.
아래 코드 스니펫은 이 작업을 수행하는 방법을 보여줍니다.
<igx-query-builder #queryBuilder [entities]="this.entities">
<igx-query-builder-header [title]="'Query Builder Template Sample'">
</igx-query-builder-header>
</igx-query-builder>
Search value
The search value of a condition can be templated using the igxQueryBuilderSearchValue directive, applied to an <ng-template> inside of the igx-query-builder's body:
<igx-query-builder #queryBuilder
[entities]="entities"
[expressionTree]="expressionTree">
<ng-template #searchValueTemplate
igxQueryBuilderSearchValue
let-searchValue
let-selectedField = "selectedField"
let-selectedCondition = "selectedCondition"
let-defaultSearchValueTemplate = "defaultSearchValueTemplate">
@if (
selectedField?.field === 'Region' &&
(selectedCondition === 'equals' || selectedCondition === 'doesNotEqual')
){
<igx-select [placeholder]="'Select region'" [(ngModel)]="searchValue.value">
<igx-select-item *ngFor="let reg of regionOptions" [value]="reg">
{{ reg.text }}
</igx-select-item>
</igx-select>
}
@else if (
selectedField?.field === 'OrderStatus' &&
(selectedCondition === 'equals' || selectedCondition === 'doesNotEqual')
){
<igx-radio-group>
<igx-radio class="radio-sample"
*ngFor="let stat of statusOptions"
value="{{stat.value}}"
[(ngModel)]="searchValue.value">
{{stat.text}}
</igx-radio>
</igx-radio-group>
}
@else {
<ng-container #defaultTemplate *ngTemplateOutlet="defaultSearchValueTemplate"></ng-container>
}
</ng-template>
</igx-query-builder>
Formatter
조건이 편집 모드가 아닐 때 표시되는 칩의 검색 값 모양을 변경하려면 fields 배열에 formatmatter 함수를 설정할 수 있습니다. 검색 값과 선택한 조건은 다음과 같이 value 및 rowData 인수를 통해 액세스할 수 있습니다.
this.ordersFields = [
{ field: "CompanyID", dataType: "string" },
{ field: "OrderID", dataType: "number" },
{ field: "EmployeeId", dataType: "number" },
{ field: "OrderDate", dataType: "date" },
{ field: "RequiredDate", dataType: "date" },
{ field: "ShippedDate", dataType: "date" },
{ field: "ShipVia", dataType: "number" },
{ field: "Freight", dataType: "number" },
{ field: "ShipName", dataType: "string" },
{ field: "ShipCity", dataType: "string" },
{ field: "ShipPostalCode", dataType: "string" },
{ field: "ShipCountry", dataType: "string" },
{ field: "Region", dataType: "string", formatter: (value: any, rowData: any) => rowData === 'equals' || rowData === 'doesNotEqual' ? `${value.value}` : value }},
{ field: "OrderStatus", dataType: "number" }
];
Demo
Angular Query Builder 구성 요소의 헤더와 검색 값에 대한 템플릿 및 포맷터 기능을 보여주기 위해 이 Angular Query Builder 예제를 만들었습니다.
스타일링
To get started with styling the Query Builder, we need to import the index file, where all the theme functions and component mixins live:
@use "igniteui-angular/theming" as *;
// IMPORTANT: Prior to Ignite UI for Angular version 13 use:
// @import '~igniteui-angular/lib/core/styles/themes/index';
The Query Builder takes its background color from the its theme, using the background parameter. In order to change the background we need to create a custom theme:
$custom-query-builder: query-builder-theme(
$schema: $dark-material-schema,
$background: #292826,
...
);
쿼리 빌더 내부에는 버튼, 칩, 드롭다운, 입력과 같은 다른 구성 요소가 있으므로 각 구성 요소에 대해 별도의 테마를 만들어야 합니다.
$custom-button: flat-button-theme(
$schema: $dark-material-schema,
$foreground: #ffcd0f,
);
$custom-input-group: input-group-theme(
$schema: $dark-material-schema,
$focused-secondary-color: #ffcd0f
);
$custom-chip: chip-theme(
$schema: $dark-material-schema,
$background: #ffcd0f,
);
$custom-icon-button: outlined-icon-button-theme(
$schema: $dark-material-schema,
$foreground: #ffcd0f,
);
In this example we only changed some of the parameters for the listed components, but the button-theme, chip-theme, drop-down-theme, input-group-theme themes provide way more parameters to control their respective styling.
Note
우리가 방금 한 것처럼 색상 값을 하드코딩하는 대신, andpalette 함수를 사용color 해 색상 측면에서 더 큰 유연성을 얻을 수 있습니다. 사용 방법에 대한 자세한 안내는 해당 주제를 참고Palettes 해 주세요.
The last step is to include the new component themes using the css-vars mixin.
@include css-vars($custom-query-builder);
:host {
::ng-deep {
@include css-vars($custom-input-group);
@include css-vars($custom-chip);
@include css-vars($custom-icon-button);
.igx-filter-tree__buttons {
@include css-vars($custom-button);
}
}
}
Note
If the component is using an Emulated ViewEncapsulation, it is necessary to penetrate this encapsulation using ::ng-deep to style the components inside the query builder component (button, chip, drop-down ...etc).
Demo
Note
샘플은 선택된 글로벌 테마Change Theme의 영향을 받지 않습니다.
또한 실제 UI 구성 요소와 함께 WYSIWYG App Builder ™사용하여 Angular 앱 개발을 간소화할 수 있습니다.
API References
- IgxQueryBuilderComponent API
- IgxQueryBuilderHeaderComponent
- IgxQueryBuilderSearchValueTemplate지시어
- IgxQueryBuilderComponent 스타일