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).
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.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With