0

Hello I have 4 different components that use the same browser listening logic I've implemented like here:

@Component(...)
export class FooComponent {
 
  k = false;

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

Which corresponds to the HTML component here:

<button
  [ngClass]="k ? 'mdc-fab--mini' : 'mdc-fab--extended'"
  class="mdc-fab mdc-fab--touch"
  (click)="openQr()"
>
  Foo Button
</button>

If k is true , the class 'mdc-fab--mini' should be applied and vice-versa.

When I resize the browser screen it works as intended, but the moment I route to another component with this same lines of code (HTML and the typescript logic), the class 'mdc-fab--mini' is not applied and instead the 'mdc-fab--extended' is applied even though the browser window is less than 768px.

Is there a reason for this?

IDK4real
  • 757
  • 6
  • 14
  • Your code is executed when window is resized, not when navigation completes. Did not test that, but maybe something like `ngAfterViewInit() { this.onResize(null) }` will do the trick, i.e. your component will get correct value for `k` the moment it appears on the screen, and then `k` will be updated again when user resizes window. – alx Nov 13 '21 at 00:59
  • whats onResize? – user17399782 Nov 13 '21 at 01:56
  • That's the method from your code above: `onResize(event) { ... }`. – alx Nov 14 '21 at 09:04

1 Answers1

0

The reason why your code fails is because you are listening for a window resize event which is only fired when a window resize occurs.

What you are doing is:

  1. Create a component -> the listener is not fired;
  2. Resize the browser -> the listener fires;
  3. Change to new component -> a new listener is created after the resize occurs.

So no new resize event occurred for your new component to listen to.


The issue then becomes, how do we fix this?

The best approach is to create a service that holds the current screen status and allows any component that wants to list to it.

Doing so prevents the duplication of code across your components and ensures that if you need to implement further behavior connected to your browser size, it can easily be done.

You can find several examples on how to create such a service in the Angular Window resize event StackOverflow.

IDK4real
  • 757
  • 6
  • 14