Visão geral da diretiva Angular Virtual ForOf

    A diretiva igxForOf Ignite UI for Angular é uma alternativa ao ngForOf para criar modelos de grandes quantidades de dados. Ela usa virtualização nos bastidores para otimizar a renderização do DOM e o consumo de memória.

    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
    

    Para obter uma introdução completa ao Ignite UI for Angular, leia o tópico de introdução.

    O próximo passo é importar issoIgxForOfModule no seu arquivo 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 {}
    

    Alternativamente,16.0.0 você pode importar comoIgxForOfDirective uma dependência independente.

    // 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>
    

    A propriedade de dados é uma matriz que fornece os objetos de dados usados para construir o DOM virtualizado.

    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.

    Siga o tópico Virtualização de grade para obter informações e demonstrações mais detalhadas.

    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

    Limitação Descrição
    scrollToo método não funciona corretamente quando o tamanho do conteúdo dos modelos renderizados muda após a inicialização Quando os elementos dentro do modelo têm um tamanho que muda o tempo de execução após a inicialização (por exemplo, como resultado da projeção de conteúdo, resolução de solicitação remota etc.), então oscrollTo o método não conseguirá rolar para o índice correto. O método rolará para a posição do índice antes que a alteração do tamanho do tempo de execução ocorra, portanto, o local não estará correto depois que o tamanho for alterado posteriormente. Uma possível solução alternativa é usar modelos que não alterem seu tamanho com base em seu conteúdo se o conteúdo for carregado posteriormente.

    API References

    Additional Resources

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