Wojciech Kaczor
Wojciech Kaczor

Reputation: 71

Angular - Change CSS property with NgStyle dynamically

I have div element which I want to show or no depending on the screen size (I know that can be done by mediaqueries, but tried to approach this with Angular). So I got working NgStyle condition [ngStyle]="{display: innerWidth < '600' ? 'none' : 'flex'}" when innerWidth is variable in the .ts file of this component

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

This is working fine, but changing only when I reload the page, so I want to trigger this change dynamically when I resize the browser window, is that possible in similar way?

Upvotes: 2

Views: 1348

Answers (1)

aw04
aw04

Reputation: 11177

You'll need to update the value when the window is resized. You can listen for window:resize:

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

Upvotes: 5

Related Questions