在我的Angular 2
应用中,我根据浏览器窗口宽度更改样式。这是一个样本(SCSS):
.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;
}
}
这使我的UI响应。我希望我的Angular组件知道哪个宽度间隔是最新的:
/* 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";
}
组件将调用此函数并根据宽度调整其行为。例如,下面的模板将在更宽的屏幕上显示更多内容:
<div>
{{getWidthRange()==='small'? shortText : longText}}
</div>
更好的是,我会设置一个Observable,当浏览器从一个范围转换到下一个范围时发出:
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
然后,组件可以订阅widthRangeChanges
并在收到新范围时更新模型值。如何在Angular 2
?
Angular 2 rc-6
,typescript 2.0.2
,rxjs 5 beta 11
答案 0 :(得分:14)
您可以使用RxJS的fromEvent
运算符:
const $resizeEvent = Observable.fromEvent(window, 'resize')
.map(() => {
return document.documentElement.clientWidth;
})
.debounceTime(200)
$resizeEvent.subscribe(data => {
this.width = data;
});
<强> Plunker Example 强>
答案 1 :(得分:4)
<强>模板强>
<div (window:resize)="onResize($event)"></div>
export class AppComponent {
onResize(event) {
console.log(event);
console.log("width:" + event.target.innerWidth);
console.log("height:" + event.target.innerHeight);
this.pixelWidth = event.target.innerWidth;
}
getWidthRange(){
if(this.pixelWidth < 251) return "small";
if(this.pixelWidth < 451) return "medium";
return "large";
}
}
答案 2 :(得分:0)
sel.select_by_visible_text("External Checking 6771: f12000066")