如何根据媒体查询动态传递值

问题描述 投票:2回答:2

在我的产品部分有大约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>
css angular typescript angular7
2个回答
0
投票

你可以使用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);
}

0
投票

获得init的窗口宽度

public innerWidth: any;
ngOnInit() {
  this.innerWidth = window.innerWidth;
}

如果你想在调整大小时保持更新:

@HostListener('window:resize', ['$event'])
onResize(event) {
  this.innerWidth = window.innerWidth;
}

您可以使用此代码检查窗口大小是否为1600px to 1200px1199 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;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.