首页 > 解决方案 > 角度材料保存和恢复pageSize到localStorage

问题描述

我想将 pageSize 保存并恢复到 localStorage。首先,在我的脑海中,我创建了一个指令。它部分工作:) 我可以保存 pageSize。但是怎么读呢?

请强大的所有人提示我!

import { Directive, ElementRef, OnDestroy, HostListener, HostBinding } from 

'@angular/core';
import { UserClientOptionsService } from 'app/user-client-options.service';

@Directive({
  selector: '[itemsPerPage]'
})
export class ItemsPerPageDirective implements OnDestroy {

  constructor(private element: ElementRef, private optionsService: UserClientOptionsService) {
  }

  // it doesn't work. No property pageSize exists
  //@HostBinding('pageSize')
  //pageSize: number;

  @HostListener('page', ['$event'])
  onChange(e) {
    this.optionsService.update(x => x.itemsPerPage = e.pageSize);
  }

  ngOnDestroy() {
  }
}

和HTML:

<mat-paginator [length]="src" pageSize="10" itemsPerPage [pageSizeOptions]="[5, 10, 20]"></mat-paginator>

标签: angularangular-material

解决方案


受@Marshal 代码的启发,我尝试自己创建一个持久的pageSize。

我创建了一个新指令mPaginationItemsPerPage

import { Directive, OnInit } from '@angular/core';
import { MatPaginator, PageEvent } from '@angular/material';

const PAGE_SIZE_KEY = 'pagination_page_size';

@Directive({
    selector: '[mPaginationItemsPerPage]'
})
export class PaginationItemsPerPageDirective implements OnInit {
    private element: MatPaginator;

    get pageSize() {
        return parseInt(localStorage.getItem(PAGE_SIZE_KEY), 10);
    }

    set pageSize(size: number) {
        localStorage.setItem(PAGE_SIZE_KEY, '' + size);
    }

    constructor(private el: MatPaginator) {
        this.element = el;
    }

    ngOnInit(): void {
        this.element.pageSize = this.pageSize;

        this.element.page.subscribe((page: PageEvent) => {
            this.pageSize = page.pageSize;
        });
    }
}

您所要做的就是向mat-paginator元素添加指令属性:

<mat-paginator mPaginationItemsPerPage [length]="count" [hidePageSize]="false" [pageSize]="10" [pageSizeOptions]="[10,25,50,100]"></mat-paginator>

推荐阅读