在我的产品部分有大约300种产品,因此对于分页我使用了ngx-pagination插件。因此应该根据媒体查询显示产品。例如,我必须传递1600px到1200px的值(在媒体查询中)应该有itemsPerPage:30
,1199到768 itemsPerPage:24
怎么做到这一点?
<ecom-section-box>
<ecom-card-wc-5 *ngFor="let data of dataArray4 | paginate: { itemsPerPage: 30, currentPage: p } " [data]="data"></ecom-card-wc-5>
</ecom-section-box>
<div class="card card2">
<span class="pagination-alignment">
<pagination-controls (pageChange)="p = $event" ></pagination-controls>
</span>
</div>
你可以使用BreakpointObserver
的@angular/cdk/layout
。
import {BreakpointObserver, Breakpoints} from '@angular/cdk/layout';
import { map, filter } from 'rxjs/operators'
import { merge } from 'rxjs'
queryValues = new Map([
['(min-width: 768px) and (max-width: 1199px)', 24],
['(min-width: 1200px) and (max-width: 1600px)', 30],
]);
itemsPerPage: number;
constructor(private breakpointObserver: BreakpointObserver) { }
ngOnInit() {
merge(...Array.from(this.queryValues.keys()).map(q => this.breakpointObserver.observe(q)))
.pipe(
filter(state => state.matches),
map(state => this.queryValues.get(Object.keys(state.breakpoints)[0]))
)
.subscribe(value => this.itemsPerPage = value);
}
获得init
的窗口宽度
public innerWidth: any;
ngOnInit() {
this.innerWidth = window.innerWidth;
}
如果你想在调整大小时保持更新:
@HostListener('window:resize', ['$event'])
onResize(event) {
this.innerWidth = window.innerWidth;
}
您可以使用此代码检查窗口大小是否为1600px to 1200px
或1199 to 768
并相应地设置itemsPerPage
。
如何使用此代码:
@HostListener('window:resize', ['$event'])
onResize(event) {
this.innerWidth = window.innerWidth;
if (this.innerWidth <= 1600 && this.innerWidth >= 1200) {
itemsPerPage = 30;
} else if (this.innerWidth <= 1199 && this.innerWidth >= 768) {
itemsPerPage = 24;
}
}