如果宽度组件的DOM元素改变了,我必须重新计算一些东西。在没有Angular的情况下,我是这样解决的:
var old_width = $("#container").width();
update();
$(window).on('resize',function() {
var new_width = $("#container").width();
if(old_width != new_width) {
old_width = new_width;
update();
}
});我想用Angular来解决这个问题。不幸的是,常规元素没有resize事件,但我想以某种方式侦听它。我可以像在我的JQuery解决方案中一样使用setInterval或window.resize,但我希望我能够用Angular以更好的方式管理它。
MutationObserver不起作用,因为它监听属性的变化,但我要找的是计算样式的变化。
发布于 2017-09-24 23:09:10
我将给出一个例子,说明我是如何使用窗口调整大小来设计iphone组件的。这样,您可能会更好地了解如何使用它。下面是我的html
<div class="main-add" (window:resize)="onResize($event)"
[style.margin-left]="addMarginLeft">
<img (click)="onAdd()" src="/images2/iphone7-add.jpeg"
[style.width]="addWidth">
</div>
<rb-product-list [query]="productQuery"></rb-product-list> 下面是我的组件
ngOnInit()
this.getAddResponsive();
}
onResize(event: any) {
this.getAddResponsive();
}
getAddResponsive(){
this.addWidth = 1000 + 'px';
let delta = (window.innerWidth - 1000)*.5 ;
if(delta > 0)
this.addMarginLeft = delta + 'px';
else {
if((window.innerWidth - 20) > 530)
this.addWidth = window.innerWidth - 20 + 'px';
else this.addWidth = '530px';
this.addMarginLeft = '0px';
}
}下面是它的外观。希望这能有所帮助。

发布于 2017-09-25 02:08:49
可以使用HostListener监听resize事件。值流是RxJS观察值的完美用例,它们提供了开箱即用的高级别控制:
resizeSubject = new Subject();
@HostListener('window:resize', ['$event'])
resizeListener(e) {
this.resizeSubject.next({
width: e.target.innerWidth,
height: e.target.innerHeight,
});
}
ngOnInit() {
this.resizeSubscription = this.resizeSubject.asObservable()
.debounceTime(100)
.map(({ width }) => width)
.distinctUntilChanged()
.subscribe(width => {
// Debounced width, value changes only
console.log(width);
});
}
ngOnDestroy() {
this.resizeSubscription.unsubscribe();
}https://stackoverflow.com/questions/46391095
复制相似问题