Angular Virtual ForOf 지시문 개요

    Ignite UI for Angular 대량의 데이터를 템플릿화하기 위한 ngForOf의 대안입니다. 이는 가상화를 백그라운드에서 사용하여 DOM 렌더링과 메모리 소비를 최적화합니다.

    Angular Virtual For Directive Example

    Getting Started with Ignite UI for Angular Virtual ForOf Directive

    To get started with the Ignite UI for Angular igxFor directive, first you need to install Ignite UI for Angular. In an existing Angular application, type the following command:

    ng add igniteui-angular
    

    Ignite UI for Angular에 대한 전체 소개는 시작 항목을 참조하십시오.

    다음 단계는 다음 단계를 가져오는 것입니다.IgxForOfModule 당신의 app.module.ts 파일.

    // app.module.ts
    
    import { IgxForOfModule } from 'igniteui-angular/directives';
    // import { IgxForOfModule } from '@infragistics/igniteui-angular'; for licensed package
    
    @NgModule({
        imports: [
            ...
            IgxForOfModule,
            ...
        ]
    })
    export class AppModule {}
    

    또는16.0.0 독립 실행형 의존성으로 가져올IgxForOfDirective 수도 있습니다.

    // home.component.ts
    
    import { IgxForOfDirective } from 'igniteui-angular/directives';
    // import { IgxForOfDirective } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
        selector: 'app-home',
        template: `
        <span #container>
            <ng-template *igxFor="data"></ng-template>
        </span>
        `,
        styleUrls: ['home.component.scss'],
        standalone: true,
        imports: [IgxForOfDirective]
    })
    export class HomeComponent {
        public data: Employee [];
    }
    

    Now that you have the Ignite UI for Angular Tree Grid module or directives imported, you can start using the igxFor directive.

    Using the Angular Virtual ForOf

    Now that we have the module or directive imported, let’s get started with a basic configuration of the igxFor that binds to local data:

    <span #container>
        <ng-template *igxFor="data"></ng-template>
    </span>
    

    data 속성은 가상화된 DOM을 구성하는 데 사용되는 데이터 개체를 제공하는 배열입니다.

    Examples

    The igxFor directive can be used to virtualize the data in vertical, horizontal or both directions.

    Virtualization works similarly to Paging by slicing the data into smaller chucks which are swapped from a container viewport while the user scrolls the data horizontally/vertically. The difference with the Paging is that virtualization mimics the natural behavior of the scrollbar. The igxFor directive is creating scrollable containers and renders small chunks of the data. It is used inside the igxGrid and it can be used to build a virtual igx-list.

    Vertical virtualization

    <igx-list>
        <div [style.height]="'500px'" [style.overflow]="'hidden'" [style.position]="'relative'">
            <igx-list-item [style.width]="'calc(100% - 18px)'"
                *igxFor="let item of data | igxFilter: fo;
                         scrollOrientation : 'vertical';
                         containerSize: '500px'; 
                         itemSize: '50px'">
                <div class="contact">
                    <span class="name">{{item.name}}</span>
                </div>
            </igx-list-item>
        </div>
    </igx-list>
    

    Note: It is strongly advised that the parent container of the igxForOf template has the following CSS rules applied: height for vertical and width for horizontal, overflow: hidden and position: relative. This is because the smooth scrolling behavior is achieved through content offsets that could visually affect other parts of the page if they remain visible.

    Horizontal virtualization

    <igx-list>
        <div [style.width]="'880px'" [style.overflow]="'hidden'" [style.position]="'relative'">
            <igx-list-item [style.width]="'220px'"
                *igxFor="let item of data | igxFilter: fo;
                         scrollOrientation : 'horizontal'; 
                         containerSize: '880px'; 
                         itemSize: '220px'">
                <div class="contact">
                    <span class="name">{{item.name}}</span>
                </div>
            </igx-list-item>
        </div>
    </igx-list>
    

    Horizontal and vertical virtualization

    <table #container [style.width]='width' 
        [style.height]='height'
        [style.overflow]='"hidden"'
        [style.position]='"relative"'>
        <ng-template #scrollContainer igxFor let-rowData
            [igxForOf]="data"
            [igxForScrollOrientation]="'vertical'"
            [igxForContainerSize]='height'
            [igxForItemSize]='"50px"'>
            <tr [style.display]="'flex'" [style.height]="'50px'">
                <ng-template #childContainer igxFor let-col
                    [igxForOf]="cols"
                    [igxForScrollOrientation]="'horizontal'"
                    [igxForScrollContainer]="parentVirtDir"
                    [igxForContainerSize]='width'>
                        <td [style.min-width]='col.width + "px"'>
                            {{rowData[col.field]}}
                        </td>
                </ng-template>
            </tr>
        </ng-template>
    </table>
    

    The igxFor directive is used to virtualize data in both vertical and horizontal directions inside the igxGrid.

    자세한 정보와 데모를 보려면 그리드 가상화 주제를 따르십시오.

    igxFor bound to remote service

    The igxForOf directive can be bound to a remote service using the Observable property - remoteData (in the following case). The chunkLoading event should also be utilized to trigger the requests for data.

    <div style='height: 500px; overflow: hidden; position: relative;'>
        <ng-template igxFor let-item [igxForOf]="remoteData | async"
            (chunkPreload)="chunkLoading($event)"
            [igxForScrollOrientation]="'vertical'"
            [igxForContainerSize]='"500px"'
            [igxForItemSize]='"50px"'
            [igxForRemote]='true'
            let-rowIndex="index" #virtDirRemote>
            <div style='height:50px;'>{{item.ProductID}} : {{item.ProductName}}</div>
        </ng-template>
    </div>
    

    Note: There is a requirement to set the totalItemCount property in the instance of igxForOf.

    this.virtDirRemote.totalItemCount = data['@odata.count'];
    

    In order to access the directive instance from the component, it should be marked as ViewChild:

    @ViewChild('virtDirRemote', { read: IgxForOfDirective })
    public virtDirRemote: IgxForOfDirective<any>;
    

    After the request for loading the first chunk, the totalItemCount can be set:

    public ngAfterViewInit() {
        this.remoteService.getData(this.virtDirRemote.state, (data) => {
            this.virtDirRemote.totalItemCount = data['@odata.count'];
        });
    }
    

    When requesting data you can take advantage of the IgxForOfState interface, which provides the startIndex and chunkSize properties. Note that initially the chunkSize will be 0, so you have to specify the size of the first loaded chunk (the best value is the initial igxForContainerSize divided by the igxForItemSize).

    public getData(data?: IForOfState, cb?: (any) => void): any {
        var dataState = data;
        return this.http
            .get(this.buildUrl(dataState))
            .map((response) => response.json())
            .map((response) => {
                return response;
            })
            .subscribe((data) => {
                this._remoteData.next(data.value);
                if (cb) {
                    cb(data);
                }
            });
    }
    
    private buildUrl(dataState: any): string {
        let qS: string = '?', requiredChunkSize: number;
        if (dataState) {
            const skip = dataState.startIndex;
                requiredChunkSize =  dataState.chunkSize === 0 ?
                // Set initial chunk size, the best value is igxForContainerSize
                // initially divided by igxForItemSize
                10 : dataState.chunkSize;
            const top = requiredChunkSize;
            qS += `$skip=${skip}&$top=${top}&$count=true`;
        }
        return `${this.url}${qS}`;
    }
    

    Every time the chunkPreload event is thrown, a new chunk of data should be requested:

    chunkLoading(evt) {
        if(this.prevRequest){
            this.prevRequest.unsubscribe();
         }
         this.prevRequest = this.remoteService.getData(evt, ()=> {
            this.virtDirRemote.cdr.detectChanges();
        });
    }
    

    Local Variables

    The igxFor directive includes the following helper properties in its context: even, odd, first and last. They are used to identify the current element position in the collection. The following code snippet demonstrates how to use the even property in an ng-template. Аn even class will be assigned to every even div element:

    <ng-template igxFor let-item let-isEven="even"
                 [igxForOf]="data" 
                 [igxForScrollOrientation]="'vertical'" >
        <div [ngClass]="{even: isEven}"></div>
    </ng-template>
    

    Known Limitations

    한정 설명
    scrollTo초기화 후 렌더링된 템플릿의 콘텐츠 크기가 변경되면 메서드가 올바르게 작동하지 않습니다. 템플릿 내부 요소의 크기가 초기화 후 런타임을 변경하는 경우(예: 콘텐츠 프로젝션, 원격 요청 해결 등의 결과로)scrollTo 메소드는 올바른 인덱스로 스크롤할 수 없습니다. 메서드는 런타임 크기가 변경되기 전에 인덱스 위치로 스크롤하므로 나중에 크기가 변경된 후에는 위치가 정확하지 않습니다. 가능한 해결 방법은 콘텐츠가 나중에 로드되는 경우 콘텐츠에 따라 크기가 변경되지 않는 템플릿을 사용하는 것입니다.

    API References

    Additional Resources

    Our community is active and always welcoming to new ideas. * [Ignite UI for Angular **Forums**](https://ko.infragistics.com/community/forums/f/ignite-ui-for-angular) * [Ignite UI for Angular **GitHub**](https://github.com/IgniteUI/igniteui-angular)