简体   繁体   中英

How to call a function, if the width of the component's DOM element is changed? (Angular4)

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.

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. 在此处输入图片说明

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM