One of the challenges I faced in my Angular 2
application was implementing responsive design by adjusting styles based on browser window width. Below is a snippet of SCSS code showing how I achieved this:
.content{
/*styles for narrow screens*/
@media (max-width: 750px){
background-color:beige;
}
/*styles for medium screens*/
@media (min-width: 751px) and (max-width: 1200px) {
background-color:red;
}
/*styles for wide screens*/
@media (min-width: 1201px) {
background-color:brown;
}
}
To make it easier for Angular components to respond accordingly, I created a function that determines the current width interval based on pixel values:
/* Returns which of the CSS width intervals is current*/
getWidthRange(){
let pixelWidth = ...; //what goes here?
if(pixelWidth < 251) return "small";
if(pixelWidth < 451) return "medium";
return "large";
}
Each component can use this function to adjust its behavior. For example, a template might display different content based on the screen width:
<div>
{{getWidthRange()==='small'? shortText : longText}}
</div>
In addition to this, I wanted to set up an Observable that notifies components when the browser transitions between different width ranges:
widthRangeChanges = Observable.create( observer =>
{
// ? how to detect when width changes
let oldRange = '...';
let newRange = '...';
if(newRange!==oldRange) observer.next(newRange);
}
).share(); //all subscribers share same output channel
This way, components can subscribe to widthRangeChanges
and update their model values accordingly. Implementing this in Angular 2
rc-6 with typescript 2.0.2
and rxjs 5 beta 11
was indeed challenging, but worth the effort.