Is there an Angular 2 service that is similar to $mdMedia? I need to show or hide a button based on the size of the window (if the window is the same size as the screen, I want to hide it)
Asked
Active
Viewed 923 times
2 Answers
1
Maybe this could help you.
resize.service.js
import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
@Injectable()
export class ResizeService {
public window = new BehaviorSubject(null);
constructor() {
window.onresize = (e) => {
this.window.next(e.target);
};
}
}
app.component.ts
import {Component} from '@angular/core';
import {ResizeService} from './resize/resize.service';
@Component({
moduleId: module.id,
selector: 'my-app',
templateUrl: 'app.component.html',
providers: [ResizeService]
})
export class AppComponent {
constructor(private resizeService: ResizeService) {
resizeService.window.subscribe((val) => {
if (val) {
console.log(val.innerWidth);
}
});
};
}
The service uses BehaviourSubject. See this answer for a description of what it is. Also see https://xgrommx.github.io/rx-book/content/subjects/behavior_subject/index.html
The component subscribes to the BehaviourSubject (window) and gets the updated values when the screen size changes.

Community
- 1
- 1

camden_kid
- 12,591
- 11
- 52
- 88
1
You can use and should use flex-layout:
official https://github.com/angular/flex-layout/wiki/Adaptive-Layouts#core-directives--responsive-features
import {ObservableMedia} from '@angular/flex-layout';
@Component({
selector : 'my-mobile-component',
template : `
<div *ngIf="media.isActive('xs')">
This content is only shown on Mobile devices
</div>
<footer>
Current state: {{ }}
</footer>
`
})
export class MyMobileComponent {
public state = '';
constructor(public media:ObservableMedia ) {
media.asObservable()
.subscribe((change:MediaChange) => {
this.state = change ? `'${change.mqAlias}' = (${change.mediaQuery})` : ""
});
}
}

hehe
- 227
- 5
- 15