0

I'm trying to render a div based on whether or not the screen is a certain size. I am able to do this when the page initially loads, however I'm not understanding how to do so when the window changes size AFTER the page loads. I would like a div to either be a "mobile" div or "!mobile" div depending on current screen size.

Here is the relevant code for my home.component.ts file:

import { Component, OnInit, HostListener } from '@angular/core';

export class HomeComponent implements OnInit {
  mobile: Boolean;
}

ngOnInit() {
    if (window.screen.width <= 615) {
      this.mobile = true;
    } else if (window.screen.width >= 616) {
      this.mobile = false;
    }

  @HostListener('window:resize', ['$event'])
  onResize(event) {
    if (event.target.innerWidth <= 767) {
      this.mobile = true;
      this.ngOnInit();
    } else if (event.target.innerWidth >= 768) {
      this.mobile = false;
      this.ngOnInit();
    }
  }

and here is my home.component.html file div's:

<ngb-carousel (window:resize)="onResize($event) *ngIf="mobile">
     <!-- ...additional content within mobile div -->
</ngb-carousel>


 <div (window:resize)="onResize($event) *ngIf="!mobile" class="homepage-img-card row ml-5">
     <!-- ...additional content within non-mobile div -->
</div>

Not sure how to correctly bind what's happening in the HostListener to the html in order to render the desired div based on the current window size. I know the HostListener part is working, since I'm able to console.log the current screen size (not included in my example).

R. Richards
  • 24,603
  • 10
  • 64
  • 64
Jon
  • 622
  • 8
  • 29
  • Does this answer your question? [Angular window resize event](https://stackoverflow.com/questions/35527456/angular-window-resize-event) – Shabbir Dhangot Sep 25 '20 at 06:29
  • don't do this using javascript, use [CSS](https://stackoverflow.com/a/64054133/542251). Read up on [responsive design](https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Responsive_Design) – Liam Sep 25 '20 at 07:22

1 Answers1

2

Why not use Media Query-based CSS rules?

Some simple media query rules in your stylesheet should work much more simply, and not require browser script engine time or angular ngOnInit() cycles. Try this:

/* CSS */

ngb-carousel {
  display: none;
}
.homepage-img-card {
  display: block;
}

@media screen and (max-width: 767px) {
  ngb-carousel {
    display: block;
  }
  .homepage-img-card {
    display: none;
  }
}

You can dispense then with all of the typescript. These CSS rules will be enough and will apply immediately and seamlessly whenever the viewport is resized.

Tony Brasunas
  • 4,012
  • 3
  • 39
  • 51
  • 1
    Great, thank you. Yeah, I guess it does make more sense to use CSS only for this. – Jon Sep 25 '20 at 13:18