function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Angel ZAngel Z 

lightning web component on window resize

Hello!

I am trying to show/hide text dynamically on window resize but it doesn't work. Here's the code:
 
<template>
     <template if:true={resolutionLessThan768}>
          resolutionLessThan768
     </template>
     <template if:true={resolutionLessThan1280}>
        resolutionLessThan1280
     </template>
     <template if:true={resolutionGreaterThan1280}>
        resolutionGreaterThan1280
     </template>
</template>
export default class lwc extends LightningElement {
    
    resolutionLessThan1280 = false;
    resolutionLessThan768 = false;
    resolutionGreaterThan1280 = false;

    
    pageLayoutChanged(){
        if (window.innerWidth < 768) {
            this.resolutionLessThan768 = true;
        }
        else if (window.innerWidth >= 768 && window.innerWidth < 1280) { 
            this.resolutionLessThan1280 = true;
        }
        else if(window.innerWidth >= 1280) {
            this.resolutionGreaterThan1280 = true;
        }
        
    }

   connectedCallback() {      
        this.pageLayoutChanged();
    }

   renderedCallback() {
        this.pageLayoutChanged();
    }
}


Any ideas what I am missing?

Thanks
Best Answer chosen by Angel Z
ANUTEJANUTEJ (Salesforce Developers) 
Hi Angel,

Below link in shows a way to detect resize event in lightning web components 

https://salesforce.stackexchange.com/questions/281764/add-event-listener-for-window-resize-in-lightning-web-component

The code used is:

Controller:
import { LightningElement, track } from 'lwc';
export default class App extends LightningElement {
connectedCallback() {
        window.addEventListener('resize', this.myFunction);
    }
    @track count = 0;
    myFunction = () => {
        this.count = this.count += 1;
        console.log('resized => ', this.count);
    };
}

In myFunction try rendering fields conditionally as per your use case below link you can use for reference:

>> https://developer.salesforce.com/docs/component-library/documentation/en/lwc/create_conditional

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future.

Thanks.