Angular Tree Grid Summaries

    Ignite UI for Angular의 Angular UI 그리드에는 그룹 푸터로 열 수준에서 작동하는 요약 기능이 있습니다. Angular 그리드 요약은 사용자가 열 내 데이터 유형에 따라 또는 트리 그리드에서 사용자 정의 각도 템플릿을 구현하여 사전 정의된 기본 요약 항목 세트가 있는 별도의 컨테이너에서 열 정보를 볼 수 있게 해주는 강력한 기능입니다.

    Angular Tree Grid Summaries Overview Example

    Note

    열 요약은 모든 열 값의 함수 입니다. 필터링이 적용되지 않는 한 열 요약은 필터링된 결과 값의 함수 입니다.

    Tree Grid 요약은 Ignite UI for Angular에서 열 단위로 활성화할 수도 있습니다. 즉, 필요한 열에 대해서만 활성화할 수 있습니다. Tree Grid 요약은 열의 데이터 유형에 따라 미리 정의된 기본 요약 세트를 제공하므로 시간을 절약할 수 있습니다.

    For string and boolean data types, the following function is available:

    • 세다

    For number, currency and percent data types, the following functions are available:

    • 세다
    • 최대
    • 평균
    • 합집합

    For date data type, the following functions are available:

    • 세다
    • 가장 빠른
    • 최신

    사용 가능한 모든 열 데이터 유형은 공식 열 유형 항목에서 찾을 수 있습니다.

    Tree Grid summaries are enabled per-column by setting hasSummary property to true. It is also important to keep in mind that the summaries for each column are resolved according to the column data type. In the igx-tree-grid the default column data type is string, so if you want number or date specific summaries you should specify the dataType property as number or date. Note that the summary values will be displayed localized, according to the grid locale and column pipeArgs.

    <igx-tree-grid #grid1 [data]="data" [autoGenerate]="false" height="800px" width="800px" (columnInit)="initColumn($event)">
        <igx-column field="ID" header="Order ID" width="200px" [sortable]="true"></igx-column>
        <igx-column field="Name" header="Order Product" width="200px" [sortable]="true" [hasSummary]="true"></igx-column>
        <igx-column field="Units" width="200px" [editable]="true" [dataType]="'number'" [hasSummary]="true"></igx-column>
    </igx-tree-grid>
    

    The other way to enable/disable summaries for a specific column or a list of columns is to use the public method enableSummaries/disableSummaries of the igx-tree-grid.

    <igx-tree-grid #grid1 [data]="data" [autoGenerate]="false" height="800px" width="800px" (columnInit)="initColumn($event)" >
        <igx-column field="ID" header="Order ID" width="200px" [sortable]="true"></igx-column>
        <igx-column field="Name" header="Order Product" width="200px" [sortable]="true" [hasSummary]="true" ></igx-column>
        <igx-column field="Units" width="200px" [editable]="true" [dataType]="'number'" [hasSummary]="false"></igx-column>
    
    </igx-tree-grid>
    <button (click)="enableSummary()">Enable Summary</button>
    <button (click)="disableSummary()">Disable Summary </button>
    
    public enableSummary() {
        this.grid1.enableSummaries([
            {fieldName: 'Units', customSummary: this.mySummary},
            {fieldName: 'ID'}
        ]);
    }
    public disableSummary() {
        this.grid1.disableSummaries('Name');
    }
    

    Custom Tree Grid Summaries

    If these functions do not fulfill your requirements you can provide a custom summary for the specific columns. In order to achieve this you have to override one of the base classes IgxSummaryOperand, IgxNumberSummaryOperand or IgxDateSummaryOperand according to the column data type and your needs. This way you can redefine the existing function or you can add new functions. IgxSummaryOperand class provides the default implementation only for the count method. IgxNumberSummaryOperand extends IgxSummaryOperand and provides implementation for the min, max, sum and average. IgxDateSummaryOperand extends IgxSummaryOperand and additionally gives you earliest and latest.

    import { IgxSummaryResult, IgxSummaryOperand, IgxNumberSummaryOperand, IgxDateSummaryOperand } from 'igniteui-angular/core';
    // import { IgxSummaryResult, IgxSummaryOperand, IgxNumberSummaryOperand, IgxDateSummaryOperand } from '@infragistics/igniteui-angular'; for licensed package
    
    class MySummary extends IgxNumberSummaryOperand {
        constructor() {
            super();
        }
    
        operate(data?: any[]): IgxSummaryResult[] {
            const result = super.operate(data);
            result.push({
                key: 'test',
                label: 'Test',
                summaryResult: data.filter(rec => rec > 10 && rec < 30).length
            });
            return result;
        }
    }
    

    As seen in the examples, the base classes expose the operate method, so you can choose to get all default summaries and modify the result, or calculate entirely new summary results. The method returns a list of IgxSummaryResult.

    interface IgxSummaryResult {
        key: string;
        label: string;
        summaryResult: any;
    }
    

    요약을 계산하기 위해 선택적 매개변수를 사용합니다. 아래의 모든 데이터 섹션에 액세스하는 사용자 정의 요약을 참조하세요.

    Note

    In order to calculate the summary row height properly, the Tree Grid needs the operate method to always return an array of IgxSummaryResult with the proper length even when the data is empty.

    And now let's add our custom summary to the column UnitPrice. We will achieve that by setting the summaries property to the class we create below.

    <igx-tree-grid #grid1 [data]="data" [autoGenerate]="false" height="800px" width="800px" (columnInit)="initColumn($event)">
        <igx-column field="ID" header="Order ID" width="200px" [sortable]="true"></igx-column>
        <igx-column field="Name" header="Order Product" width="200px" [sortable]="true" [hasSummary]="true"></igx-column>
        <igx-column field="Units" [dataType]="'number'" width="200px" [editable]="true" [hasSummary]="true" [summaries]="mySummary"></igx-column>
        <igx-column field="UnitPrice" header="Unit Price" width="200px" [dataType]="'number'"  [dataType]="'currency'" [hasSummary]="true"></igx-column>
    </igx-tree-grid>
    
    ...
    export class GridComponent implements OnInit {
        mySummary = MySummary;
        ....
    }
    

    Custom summaries, which access all data

    Now you can access all Tree Grid data inside the custom column summary. Two additional optional parameters are introduced in the IgxSummaryOperand operate method. As you can see in the code snippet below the operate method has the following three parameters:

    • columnData - 현재 열의 값만 포함하는 배열을 제공합니다.
    • allGridData - 전체 그리드 데이터 소스를 제공합니다.
    • fieldName - 현재 열 필드
    class MySummary extends IgxNumberSummaryOperand {
        constructor() {
            super();
        }
        operate(columnData: any[], allGridData = [], fieldName?): IgxSummaryResult[] {
            const result = super.operate(allData.map(r => r[fieldName]));
            result.push({ key: 'test', label: 'Total Undelivered', summaryResult: allData.filter((rec) => rec.Discontinued).length });
            return result;
        }
    }
    

    Summary Template

    igxSummary targets the column summary providing as a context the column summary results.

    <igx-column ... [hasSummary]="true">
        <ng-template igxSummary let-summaryResults>
            <span> My custom summary template</span>
            <span>{{ summaryResults[0].label }} - {{ summaryResults[0].summaryResult }}</span>
        </ng-template>
    </igx-column>
    

    기본 요약이 정의되면 요약 영역의 높이는 요약 수가 가장 많은 열과 그리드의 크기에 따라 설계에 따라 계산됩니다. summaryRowHeight 입력 속성을 사용하여 디폴트 값을 재정의합니다. 인수로 숫자 값이 필요하며 false 값을 설정하면 그리드 바닥글의 기본 크기 조정 동작이 트리거됩니다.

    Note

    열 요약 템플릿은 열 summaryTemplate 속성을 필수 TemplateRef로 설정하여 API를 통해 정의할 수 있습니다.

    Disable Summaries

    The disabledSummaries property provides precise per-column control over the Ignite UI for Angular grid summary feature. This property enables users to customize the summaries displayed for each column in the grid, ensuring that only the most relevant and meaningful data is shown. For example, you can exclude specific summary types, such as ['count', 'min', 'max'], by specifying their summary keys in an array.

    또한 이 속성은 코드를 통해 런타임에 동적으로 수정할 수 있으므로 변화하는 응용 프로그램 상태 또는 사용자 작업에 맞게 그리드의 요약을 조정할 수 있는 유연성을 제공합니다.

    The following examples illustrate how to use the disabledSummaries property to manage summaries for different columns and exclude specific default and custom summary types in the Ignite UI for Angular grid:

    <!-- custom summaries -->
    <igx-column
        field="Units"
        header="Units"
        dataType="number"
        [hasSummary]="true"
        [summaries]="unitsSummary"
        [disabledSummaries]="['uniqueCount', 'maxDifference']"
    >
    </igx-column>
    <!-- default summaries -->
    <igx-column
        field="UnitPrice"
        header="Unit Price"
        dataType="number"
        [hasSummary]="true"
        [disabledSummaries]="['count', 'sum', 'average']"
    >
    </igx-column>
    

    For Units, custom summaries such as totalDelivered and totalNotDelivered are excluded using the disabledSummaries property.

    For UnitPrice, default summaries like count, sum, and average are disabled, leaving others like min and max active.

    At runtime, summaries can also be dynamically disabled using the disabledSummaries property. For example, you can set or update the property on specific columns programmatically to adapt the displayed summaries based on user actions or application state changes.

    Formatting summaries

    By default, summary results, produced by the built-in summary operands, are localized and formatted according to the grid locale and column pipeArgs. When using custom operands, the locale and pipeArgs are not applied. If you want to change the default appearance of the summary results, you may format them using the summaryFormatter property.

    public dateSummaryFormat(summary: IgxSummaryResult, summaryOperand: IgxSummaryOperand): string {
        const result = summary.summaryResult;
        if(summaryOperand instanceof IgxDateSummaryOperand && summary.key !== 'count'
            && result !== null && result !== undefined) {
            const pipe = new DatePipe('en-US');
            return pipe.transform(result,'MMM YYYY');
        }
        return result;
    }
    
    <igx-column ... [summaryFormatter]="dateSummaryFormat"></igx-column>
    

    Child Summaries

    The Tree Grid supports separate summaries for the root nodes and for each nested child node level. Which summaries are shown is configurable using the summaryCalculationMode property. The child level summaries can be shown before or after the child nodes using the summaryPosition property. Along with these two properties the IgxTreeGrid exposes and showSummaryOnCollapse property which allows you to determine whether the summary row stays visible when the parent node that refers to is collapsed.

    The available values of the summaryCalculationMode property are:

    • rootLevelOnly - 요약은 루트 수준 노드에 대해서만 계산됩니다.
    • childLevelsOnly - 요약은 하위 수준에 대해서만 계산됩니다.
    • rootAndChildLevels - 루트 및 하위 수준 모두에 대한 요약이 계산됩니다. 이것이 기본값입니다.

    The available values of the summaryPosition property are:

    • top - 하위 행 목록 앞에 요약 행이 나타납니다.
    • 하단 - 하위 행 목록 뒤에 요약 행이 나타납니다. 이것이 기본값입니다.

    The showSummaryOnCollapse property is boolean. Its default value is set to false, which means that the summary row would be hidden when the parent row is collapsed. If the property is set to true the summary row stays visible when parent row is collapsed.

    Note

    The summaryPosition property applies only for the child level summaries. The root level summaries appear always fixed at the bottom of the Tree Grid.

    Exporting Summaries

    There is an exportSummaries option in IgxExcelExporterOptions that specifies whether the exported data should include the grid's summaries. Default exportSummaries value is false.

    The IgxExcelExporterService will export the default summaries for all column types as their equivalent excel functions so they will continue working properly when the sheet is modified. Try it for yourself in the example below:

    The exported file includes a hidden column that holds the level of each DataRecord in the sheet. This level is used in the summaries to filter out the cells that need to be included in the summary function.

    아래 표에서 각 기본 요약에 해당하는 Excel 수식을 찾을 수 있습니다.

    데이터 형식 기능 엑셀 기능
    string, boolean 세다 ="카운트: "&COUNTIF(시작:끝, 레코드레벨)
    number, currency, percent 세다 ="카운트: "&COUNTIF(시작:끝, 레코드레벨)
    ="최소: "&MIN(IF(start:end=recordLevel, rangeStart:rangeEnd))
    최대 ="최대: "&MAX(IF(start:end=recordLevel, rangeStart:rangeEnd))
    평균 ="평균: "&AVERAGEIF(시작:끝, 기록 수준, rangeStart:rangeEnd)
    합집합 ="합계: "&SUMIF(start:end, RecordLevel, rangeStart:rangeEnd)
    date 세다 ="카운트: "&COUNTIF(시작:끝, 레코드레벨)
    가장 빠른 ="가장 빠른: "& TEXT(MIN(IF(start:end=recordLevel, rangeStart:rangeEnd)), format)
    최신 ="최신: "&TEXT(MAX(IF(start:end=recordLevel, rangeStart:rangeEnd)), 형식)

    Known Limitations

    한정 설명
    사용자 정의 요약 내보내기 사용자 정의 요약은 Excel 함수 대신 문자열로 내보내집니다.
    템플릿 요약 내보내기 템플릿 요약은 지원되지 않으며 기본 요약으로 내보내집니다.

    Keyboard Navigation

    요약 행은 다음 키보드 상호 작용을 통해 탐색할 수 있습니다.

    • UP- 한 셀 위로 이동합니다.
    • DOWN- 한 셀 아래로 이동합니다.
    • LEFT- 한 셀 왼쪽으로 이동합니다.
    • RIGHT- 한 셀 오른쪽으로 이동합니다.
    • CTRL + LEFT 또는 HOME- 가장 왼쪽 셀로 이동합니다.
    • CTRL + RIGHT 또는 END- 가장 오른쪽 셀로 이동합니다.

    스타일링

    To get started with styling the sorting behavior, 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';
    

    Following the simplest approach, we create a new theme that extends the grid-summary-theme and accepts the $background-color, $focus-background-color, $label-color, $result-color, $pinned-border-width, $pinned-border-style and $pinned-border-color parameters.

    $custom-theme: grid-summary-theme(
      $background-color: #e0f3ff,
      $focus-background-color: rgba(#94d1f7, .3),
      $label-color: #e41c77,
      $result-color: black,
      $pinned-border-width: 2px,
      $pinned-border-style: dotted,
      $pinned-border-color: #e41c77
    );
    
    Note

    Instead of hardcoding the color values like we just did, we can achieve greater flexibility in terms of colors by using the palette and color functions. Please refer to Palettes topic for detailed guidance on how to use them.

    마지막 단계는 구성 요소 사용자 지정 테마를 포함하는 것입니다.

    @include css-vars($custom-theme);
    
    Note

    If the component is using an Emulated ViewEncapsulation, it is necessary to penetrate this encapsulation using ::ng-deep:

    :host {
     ::ng-deep {
       @include css-vars($custom-theme);
     }
    }
    

    Demo

    API References

    Additional Resources

    우리 커뮤니티는 활동적이며 항상 새로운 아이디어를 환영합니다.