【问题标题】:How to call a function, if the width of the component's DOM element is changed? (Angular4)如果组件 DOM 元素的宽度发生变化,如何调用函数? (角度 4)
【发布时间】:2026-02-10 19:15:02
【问题描述】:

如果宽度组件的 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 解决这个问题。不幸的是,常规元素没有调整大小事件,但我想以某种方式倾听它。我可以在我的 JQuery 解决方案中使用 setIntervalwindow.resize,但我希望我能够使用 Angular 以更好的方式管理它。

MutationObserver 不起作用,因为它监听属性的变化,但我正在寻找的是计算样式的变化。

【问题讨论】:

    标签: javascript css angular dom-events


    【解决方案1】:

    我将举例说明我如何使用窗口调整大小来响应设计我的 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';
      }
    }
    

    下面是它的外观。希望这可以帮助。

    【讨论】:

      【解决方案2】:

      resize 事件可以用HostListener 监听。值流是 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();
      }
      

      【讨论】: