Angular 계층형 그리드 원격 데이터 작업

    Ignite UI for Angular Hierarchical Grid는 원격 가상화, 원격 정렬, 원격 필터링 등과 같은 원격 데이터 작업을 지원합니다. 이를 통해 개발자는 서버에서 이러한 작업을 수행하고, 생성된 데이터를 검색하고, 계층적 그리드에 표시할 수 있습니다.

    기본적으로 계층형 그리드는 데이터 작업을 수행하기 위해 자체 논리를 사용합니다. 계층적 그리드에 의해 노출되는 특정 입력 및 이벤트를 활용하여 이러한 작업을 원격으로 수행하고 결과 데이터를 계층적 그리드에 공급할 수 있습니다.

    Unique Column Values Strategy

    엑셀 스타일 필터링 대화상자 내의 목록 항목들은 해당 열의 고유 값을 나타냅니다. 계층적 그리드는 기본적으로 데이터 소스를 기반으로 이러한 값을 생성합니다. 원격 필터링의 경우, 그리드 데이터에 서버의 모든 데이터가 포함되지 않습니다. 고유 값을 수동으로 제공하고 필요에 따라 불러오기 위해 계층적 그리드의uniqueColumnValuesStrategy 입력을 활용할 수 있습니다. 이 입력은 실제로 세 가지 인수를 제공하는 메서드입니다:

    • - 해당 열 인스턴스입니다.
    • filteringExpressionsTree- 해당 열을 기준으로 축소된 필터링 표현식 트리입니다.
    • done- 서버에서 검색될 때 새로 생성된 열 값으로 호출되어야 하는 콜백입니다.

    개발자는 열과​ ​filteringExpressionsTree 인수에서 제공되는 정보를 기반으로 필요한 고유 열 값을 수동으로 생성한 다음 완료 콜백을 호출할 수 있습니다.

    Note

    입력이uniqueColumnValuesStrategy 제공되면, 엑셀 스타일 필터링의 기본 고유 값 생성 프로세스는 사용되지 않습니다.

    <igx-hierarchical-grid #hierarchicalGrid [primaryKey]="'Artist'" [data]="data" [filterMode]="'excelStyleFilter'"
                           [uniqueColumnValuesStrategy]="singersColumnValuesStrategy">
        ...
        <igx-row-island [primaryKey]="'Album'" [allowFiltering]="true" [filterMode]="'excelStyleFilter'"
                        [uniqueColumnValuesStrategy]="albumsColumnValuesStrategy">
            ...
        </igx-row-island>
    </igx-hierarchical-grid>
    
    public singersColumnValuesStrategy = (column: ColumnType,
                                          columnExprTree: IFilteringExpressionsTree,
                                          done: (uniqueValues: any[]) => void) => {
    // Get specific column data for the singers.
    this.remoteValuesService.getColumnData(
        null, 'Singers', column, columnExprTree, uniqueValues => done(uniqueValues));
    }
    
    public albumsColumnValuesStrategy = (column: ColumnType,
                                         columnExprTree: IFilteringExpressionsTree,
                                         done: (uniqueValues: any[]) => void) => {
    // Get specific column data for the albums of a specific singer.
    const parentRowId = (column.grid as any).foreignKey;
    this.remoteValuesService.getColumnData(
        parentRowId, 'Albums', column, columnExprTree, uniqueValues => done(uniqueValues));
    }
    

    Unique Column Values Strategy Demo

    엑셀 스타일 필터링을 위한 맞춤 로딩 템플릿을 제공하기 위해 다음igxExcelStyleLoading 지시를 사용할 수 있습니다:

    <igx-hierarchical-grid [data]="data" [filterMode]="'excelStyleFilter'" [uniqueColumnValuesStrategy]="columnValuesStrategy">
        ...
        <ng-template igxExcelStyleLoading>
            Loading ...
        </ng-template>
    </igx-hierarchical-grid>
    

    Remote Paging

    페이징 기능은 원격 데이터로 작동할 수 있습니다. 이를 시연하기 위해 먼저 데이터 가져오기를 담당할 서비스를 선언하겠습니다. 페이지 수를 계산하려면 모든 데이터 항목의 수가 필요합니다. 이 로직은 우리 서비스에 추가될 예정입니다.

    @Injectable()
    export class RemotePagingService {
        public remoteData: BehaviorSubject<any[]>;
        public dataLenght: BehaviorSubject<number> = new BehaviorSubject(0);
        public url = 'https://www.igniteui.com/api/products';
    
        constructor(private http: HttpClient) {
            this.remoteData = new BehaviorSubject([]) as any;
        }
    
        public getData(index?: number, perPage?: number): any {
            let qS = '';
    
            if (perPage) {
                qS = `?$skip=${index}&$top=${perPage}&$count=true`;
            }
    
            this.http
                .get(`${this.url + qS}`).pipe(
                    map((data: any) => data)
                ).subscribe((data) => this.remoteData.next(data));
        }
    
        public getDataLength(): any {
            return this.http.get(this.url).pipe(
                map((data: any) => data.length)
            );
        }
    }
    

    서비스를 선언한 후에는 계층적 그리드 구성 및 데이터 구독을 담당할 구성 요소를 생성해야 합니다.

    export class HGridRemotePagingSampleComponent implements OnInit, AfterViewInit, OnDestroy {
        public data: BehaviorSubject<any> = new BehaviorSubject([]);
        private _dataLengthSubscriber;
    
        constructor(private remoteService: RemotePagingService) {}
    
        public ngOnInit() {
            this.data = this.remoteService.remoteData.asObservable();
    
            this._dataLengthSubscriber = this.remoteService.getDataLength().subscribe((data) => {
                this.totalCount = data;
                this.grid1.isLoading = false;
            });
        }
    
        public ngOnDestroy() {
            if (this._dataLengthSubscriber) {
                this._dataLengthSubscriber.unsubscribe();
            }
        }
    }
    

    이제 저희가 직접 맞춤 페이징 템플릿을 설정할지, 아니면 기본igx-paginator 템플릿을 사용할 수 있겠죠. 먼저 기본 페이징 템플릿을 사용해 원격 페이징을 설정하는 데 필요한 사항을 살펴보겠습니다.

    Remote paging with default template

    기본 페이징 템플릿을 사용하려면 Paginator의totalRecords 속성을 설정해야 하며, 그래야 그리드가 전체 원격 레코드를 기반으로 전체 페이지 수를 계산할 수 있습니다. 원격 페이지네이션을 수행할 때 페이지네이터는 현재 페이지의 데이터만 그리드에 전달하므로, 그리드는 제공된 데이터 소스를 페이지네이션하려 하지 않습니다. 그래서 Grid의pagingMode 속성을 GridPagingMode.remote로 설정해야 합니다. 또한 원격 서비스에서 데이터를 가져오려면 이벤트에 구독pagingDoneperPageChange 해야 하며, 어떤 이벤트를 사용할지는 사용 사례에 따라 다릅니다.

    <igx-hierarchical-grid #hierarchicalGrid [primaryKey]="'CustomerID'" [pagingMode]="mode">
        <igx-column field="CustomerID"></igx-column>
        ...
        <igx-paginator [(page)]="page" [(perPage)]="perPage" [totalRecords]="totalCount"
            (pagingDone)="paginate($event.current)" (perPageChange)="getFirstPage()">
        </igx-paginator>
    </igx-hierarchical-grid>
    
    public totalCount = 0;
    public data: Observable<any[]>;
    public mode = GridPagingMode.remote;
    public isLoading = true;
    @ViewChild('grid1', { static: true }) public grid1: IgxGridComponent;
    
    private _dataLengthSubscriber;
    
    public set perPage(val: number) {
        this._perPage = val;
        this.paginate(0);
    }
    
    public ngOnInit() {
        this.data = this.remoteService.remoteData.asObservable();
    
        this._dataLengthSubscriber = this.remoteService.getDataLength().subscribe((data: any) => {
            this.totalCount = data;
            this.grid1.isLoading = false;
        });
    }
    
    public ngAfterViewInit() {
        const skip = this.page * this.perPage;
        this.remoteService.getData(skip, this.perPage);
    }
    
    public paginate(page: number) {
        this.page = page;
        const skip = this.page * this.perPage;
        const top = this.perPage;
    
        this.remoteService.getData(skip, top);
    }
    

    Remote Paging with custom igx-paginator-content

    커스텀 페이지네이터 콘텐츠를 정의할 때, 요청된 페이지에만 데이터를 얻고 올바른 데이터를 전달할 수 있도록 콘텐츠를 정의해야 합니다 거르다 그리고 맨 위로 선택한 페이지와 항목에 따라 원격 서비스에 대한 매개변수perPage. 우리는<igx-paginator> 예제 구성을 쉽게 하기 위해,IgxPageSizeSelectorComponent 그리고IgxPageNavigationComponent 도입된 사람들 -igx-page-size페이지별 드롭다운과 라벨을 추가합니다igx-page-nav 내비게이션 액션 버튼과 라벨을 추가할 예정입니다.

    <igx-paginator #paginator
        [totalRecords]="totalCount"
        [(perPage)]="perPage"
        [(page)]="page"
        [selectOptions]="selectOptions"
        (pageChange)="paginate($event)"
        (perPageChange)="perPageChange($event)">
        <igx-paginator-content>
            <igx-page-size></igx-page-size>
            [This is my custom content]
            <igx-page-nav></igx-page-nav>
        </igx-paginator-content>
    </igx-paginator>
    
    @ViewChild('hierarchicalGrid', { static: true }) public hierarchicalGrid: IgxHierarchicalGridComponent;
    
    public ngOnInit(): void {
        this._dataLengthSubscriber = this.remoteService.getDataLength(
            { parentID: null, rootLevel: true, key: 'Customers' }).subscribe((length) => {
                this.totalCount = length;
            });
    }
    
    public ngAfterViewInit() {
        this.hierarchicalGrid.isLoading = true;
        this._dataSubscriber = this.remoteService.getData({parentID: null, rootLevel: true, key: 'Customers' }, 0, this.perPage)
            .subscribe((data) => {
                this.hierarchicalGrid.isLoading = false;
                this.data.next(data);
            },(error) => {
                    this.hierarchicalGrid.emptyGridMessage = error.message;
                    this.hierarchicalGrid.isLoading = false;
                    this.hierarchicalGrid.cdr.detectChanges();
                }
            );
    }
    
    
    Note

    원격 페이징을 올바르게 구성하려면 다음을GridPagingMode.Remote 설정해야 합니다:

    <igx-hierarchical-grid #hierarchicalGrid [data]="data | async" [primaryKey]="'CustomerID'"
        [height]="'550px'" [width]="'100%'" [pagingMode]="mode"></igx-hierarchical-grid>
    ...
    public mode = GridPagingMode.Remote;
    

    마지막 단계는 요구 사항에 따라 페이지네이터 콘텐츠를 선언하는 것입니다.

    <igx-paginator-content>
        <igx-page-size></igx-page-size>
        [This is my custom content]
        <igx-page-nav></igx-page-nav>
    </igx-paginator-content>
    

    위의 모든 변경 후에는 다음과 같은 결과가 달성됩니다.

    Known Issues and Limitations

    • 그리드에 세트가 없primaryKey 고 원격 데이터 시나리오가 활성화되어 있을 때(페이징, 정렬, 필터링, 스크롤 시 원격 서버에 표시할 데이터를 가져오기 요청이 트리거될 때), 데이터 요청이 완료된 후 다음 상태가 줄로 사라집니다:
      • 행 선택
      • 행 확장/축소
      • 행 편집
      • 행 고정
    • 원격 데이터 시나리오에서는 격자primaryKey에 set,eventrowSelectionChanging.oldSelection 인자가 현재 데이터 뷰 밖에 있는 행의 전체 행 데이터 객체를 포함하지 않습니다. 이 경우 객체는rowSelectionChanging.oldSelection 필드 속성 중 하나primaryKey만 포함합니다. 나머지 행들은 현재 데이터 뷰에 위치해 있으며,rowSelectionChanging.oldSelection 전체 행 데이터를 포함하게 됩니다.

    API References

    Additional Resources

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