Reputation: 9279
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();
}
});
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 does not work, because it listens to changes in attributes, but what I am looking for is the change in computed style.
Upvotes: 1
Views: 548
Reputation: 222369
resize
event can be listened with HostListener
. And a stream of values is the perfect use case for RxJS observables, they provide a high level of control out of the box:
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();
}
Upvotes: 0
Reputation: 238
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>
Below is my component
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.
Upvotes: 1