如何基于媒体查询动态传递价值

时间:2019-04-30 14:46:17

标签: css angular typescript angular7

在我的产品部分中,大约有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>

2 个答案:

答案 0 :(得分:0)

要获取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;
  }
}

答案 1 :(得分:0)

您可以使用@angular/cdk/layout中的BreakpointObserver

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);
}