Tips on dynamically passing values according to media queries

Within my product section, there is a total of approximately 300 products. To implement pagination, I have utilized the ngx-pagination plugin. The products need to be displayed based on media query specifications. For example, if the viewport size falls within the range of 1600px to 1200px, the value itemsPerPage:30 should be applied; for sizes between 1199px to 768px, itemsPerPage:24 should be used.

How can this customization be achieved?

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

Answer №1

Find the window width during initialization

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

To keep it updated on resize:

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

Determining the window size as 1600px to 1200px or 1199 to 768 can help set the appropriate number of itemsPerPage.

Implementation example:

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

Answer №2

To implement responsive design in Angular, you can utilize the BreakpointObserver component available in the @angular/cdk/layout package.

import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout';
import { switchMap } from 'rxjs/operators'
import { of, EMPTY } from 'rxjs'

responsiveValues: Record<string, number> = {
  '(min-width: 768px) and (max-width: 1199px)': 24,
  '(min-width: 1200px) and (max-width: 1600px)': 30,
};

itemsPerPage: number;

constructor(private breakpointObserver: BreakpointObserver) { }

ngOnInit() {
  const queries = Object.keys(this.responsiveValues)
  this.breakpointObserver.observe(queries).pipe(
    switchMap(state => {
      const activeQuery = queries.find(q => state.breakpoints[q]);
      return activeQuery ? of(this.responsiveValues[activeQuery]) : EMPTY
    })
  ).subscribe(queryValue => this.itemsPerPage = queryValue)
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for me to create an If statement that can verify the current index within a Map?

I have the following TypeScript code snippet: export default class SingleNews extends React.Component<INews, {}> { public render(): React.ReactElement<INews> { return ( <> {this.props.featured ...

What is the most effective way to access a variable from a service in all HTML files of Angular 2/4 components?

In my angular 4 project, I have an alert service where all components can set alerts, but only specific components display them in unique locations. My question is: how can I access a variable from this service across all HTML files? The structure of my s ...

What is the best way to center align and add an icon to the header in Ionic?

How can I center align an "ion-ios-arrow-up" icon in the header of my Ionic app, similar to the concept shown below? This is my HTML template: <ion-view cache-view="false" view-title="Historical HPP"> <ion-nav-bar class="nav-title-slide-ios7 ...

Setting input autofocus in a recursive Angular2 component

Currently, I am working on creating a tree view system similar to Workflowy for practice purposes. The simple version is operational; however, I am facing difficulty in setting the input focus when adding a new component. I have experimented with various ...

What causes the position: sticky; property to fail in React implementations?

Currently, I am facing a challenge in making two sidebars sticky so that they will follow as the user scrolls until they reach the bottom of the page. In my current editing project, this implementation seems to be more complex compared to other programs w ...

CSS/Bootstrap : troubleshooting overflow problem

Experiencing a problem with the popover control due to a display issue. The overflow property had to be set to 'visible' in order to prevent it from being hidden behind the table. overflow:visible; For a repro, please see jsfiddle: http://js ...

Why is the format incorrect when the Angular 7 (Change)-Function on Input of type Date isn't functioning?

I am facing an issue with updating the date using key input and assigning the selected date to a property of my object. Below is the code I'm currently working with: <input type="date" [value]="dateTime()" (change)="setDate($event)"/> The dat ...

ExtJS web displays appear differently when viewed on Chrome's toggle device mode versus a mobile browser

Greetings, I have been working on developing a web application that can be accessed through a mobile browser. Initially, I created the web application and tested it in mobile mode using Chrome's simulation feature. https://i.sstatic.net/aAvVW.jpg H ...

Tips for customizing WTForm fields with unique CSS classes

I've recently put together a basic form snippet: class PostForm(FlaskForm): # for publishing a new blog post title = StringField("Title", validators=[DataRequired()]) submit = SubmitField('Post') The structure of my HT ...

Steps for adding a border to kendo grid row hover

One of my tasks involved creating a grid using Kendo, and I wanted to display borders on a grid row when the cursor hovers over it. I attempted the following code snippet: .k-grid > table > tbody > tr:hover, .k-grid-content > table > tbody ...

Using CSS to style the last paragraph after a heading

Trying to figure out how to style the final paragraph following a heading using CSS. I attempted using #div h1 ~ p:last-child, but it ended up skipping past the second heading and affecting the last paragraph before the list. I've been diligently sea ...

placeholder for label text in angular when no input provided

The code I have been working with is functioning correctly and displaying the data from the controller into the binding. However, when I attempted to set the server data as an empty string, I expected the default text "Your name" to appear but it did not ...

CSS Navigation Menu - Submenu displaying above main link

<div id="header"> <div class="cont"> <div id="banner"> <div id="nav"> <ul> <li><a href="index.htm">home</a></li> <li><a href="work.html">Works»</a> <ul> ...

Troubleshooting a problem with HTML table styling

Could someone please help me identify the issue with this code snippet? I am aiming to style the table with a border, background color, and align it to the top. I appreciate any assistance. Thank you. <td style="border: solid 2px #111111;" bgcolor="#d ...

Whenever I try to log in on Angular 11, I encounter the HttpErrorResponse error with a status code of

I have encountered an error and cannot seem to find a solution. Here is the code snippet: login(signInRequestPayload: SignInRequestPayload): Observable<boolean> { return this.httpClient.post<SignInResponse>( '/api/v1/registration/login&apo ...

Issue encountered while using Typescript with mocha: Unable to utilize import statement outside a module

Exploring the world of unit testing with mocha and trying to create a basic test. Project Structure node_modules package.json package-lock.json testA.ts testA.spec.ts tsconfig.json tsconfig.json { "compilerOptions": { "target&qu ...

Primeng could not locate the material theme

Within my Angular application, I have incorporated the primeng npm package using npm install. Following the instructions provided on the GetStarted page for primeng, it is mentioned that the library includes 32 free themes. However, upon exploring the node ...

Is there a way to determine the height of the ion-footer?

Is there a way to obtain the height of the ion-footer element in Ionic2? I want to calculate the initial window height minus the ion-footer height, but I am currently only able to get the overall window height. I'm not interested in retrieving the ...

Issue with absolute import in React TypeScript application

An error occurs when trying to import a module, displaying the following message: Compiled with problems: × ERROR in ./src/App.tsx 5:0-33 Module not found: Error: Can't resolve 'routes' in 'F:\Tamrinat\Porfolio\microsite ...

issues with the functionality of bootstrap modal

I'm currently working on a project where I need to set up a modal popup using bootstrap. The website I'm working on is organized by departments, so the only part of the code that I have control over is the main body of the site. I have included t ...