Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Media Queries

I want to know that does Angular 2 provides a way to determine the client's device (large screen, medium or smalls screen) or may be screen width on the basic of which some contents could be shown or hidden (removed from dom).

like image 277
Naveed Ahmed Avatar asked Jun 28 '16 17:06

Naveed Ahmed


People also ask

Can we use media queries in angular?

Use them to control when your layout can be adapted at a particular viewport or device size. Use media queries to architect your CSS by breakpoint. Media queries are a feature of CSS that allow you to conditionally apply styles based on a set of browser and operating system parameters.

What is BreakpointObserver in angular?

Luckily, Angular comes with a handy solution for these scenarios: the BreakpointObserver. Which is a utility for checking the matching state of @media queries. In this post, we will build a sample application to add the ability to configure certain breakpoints, and being able to listen to them.

What are media queries in CSS?

A media query consists of a media type and can contain one or more expressions, which resolve to either true or false. The result of the query is true if the specified media type matches the type of device the document is being displayed on and all expressions in the media query are true.


2 Answers

HostListener

One way is to use the HostListener decorator. The decorated method will be invoked when the host element emits the specified event.

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

Via ngZone

Another way is to import ngZone into your component. Then you can use NgZone to check the onresize event.

constructor(ngZone:NgZone) {
  window.onresize = (e) => {
    ngZone.run(() => {
        this.width = window.innerWidth;
        this.height = window.innerHeight;
    });
  };
}

After that you can use the [hidden] attribute to hide content depends from your width or height value.

like image 127
muetzerich Avatar answered Sep 29 '22 12:09

muetzerich


There is no need to use NgZone. There are easier ways to capture the resize window event.

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

or if you want to use if from the HTML

<div (window:resize)="onResize($event)"

onResize(event) {
  event.target.innerWidth;
}
like image 25
marianocodes Avatar answered Sep 29 '22 12:09

marianocodes