gpt4 book ai didi

Angular Material 保存并将 pageSize 恢复到 localStorage

转载 作者:太空狗 更新时间:2023-10-29 18:28:04 26 4
gpt4 key购买 nike

我想将 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>

最佳答案

受@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>

关于 Angular Material 保存并将 pageSize 恢复到 localStorage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54720787/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com