如果组件的DOM元素的宽度发生变化,如何调用函数? (Angular4) [英] How to call a function, if the width of the component's DOM element is changed? (Angular4)
问题描述
如果更改了width组件的DOM元素,我必须重新计算一些内容。没有Angular,我解决了这个问题:
I have to recalculate something, if the width component's DOM element is changed. Without Angular, I solved it like this:
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的更好方法。
I would like to solve this with Angular. Unfortunately there is no resize event for regular elements, but I would like to listen somehow for it. I could use setInterval
or window.resize
like in my JQuery solution, but I hope I am able to manage it in a better way with Angular.
MutationObserver不起作用,因为它侦听属性的变化,但我要找的是计算样式的变化。
MutationObserver does not work, because it listens to changes in attributes, but what I am looking for is the change in computed style.
推荐答案
我将举例说明如何使用窗口调整大小响应性地设计我的iphone组件。这样,您可以更好地了解如何使用它。下面是我的html
I will give an example of how I designed my iphone component responsively using window resize. This way, you may have a better understanding how to use it. Below is my 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';
}
}
下面是它的外观。希望这可以帮助。
Below is how it looks. Hope this helps.
这篇关于如果组件的DOM元素的宽度发生变化,如何调用函数? (Angular4)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!