【问题标题】:Angular2 Component listen when parent's resize changeAngular2组件在父级调整大小更改时侦听
【发布时间】:2016-09-01 23:55:57
【问题描述】:

我有一个要求,我想通过方法调用根据父组件的大小更改子组件的属性。我遇到的问题是,我唯一能听到的调整大小事件是窗口的事件,这无济于事,因为窗口大小没有改变,只有父组件是由于侧面板 div 打开和关闭。

目前我能看到的唯一可能性是进行某种轮询,我们在子组件本身内检查其宽度是否每 x 时间发生变化。

感谢您的帮助!

【问题讨论】:

标签: resize angular


【解决方案1】:

您是正确的,您无法在 div 上获取 resize 事件(无需安装一些 js 扩展)。但这样的事情是可行的。

父组件:

import {Component, AfterContentInit, ElementRef} from '@angular/core';
import { ChildComponent } from "./ChildComponent";

export interface IParentProps {
    width: number;
    height: number;
}
@Component({
    selector: 'theParent',
    template: `text text  text text text text
               text text text text text text
               <the-child [parentProps]="parentProps"></the-child>`,
    directives: [ChildComponent] 
})

export class ParentComponent implements AfterContentInit {
    sizeCheckInterval = null;
    parentProps: IParentProps = {
        width: 0,
        height: 0
    }
    constructor(private el: ElementRef) {
    }
    ngAfterContentInit() {
        this.sizeCheckInterval = setInterval(() => {
            let h = this.el.nativeElement.offsetHeight;
            let w = this.el.nativeElement.offsetWidth;
            if ((h !== this.parentProps.height) || (w !== this.parentProps.width)) {
                this.parentProps = {
                    width: w,
                    height: h

                }
            }
        }, 100);

    }
    ngOnDestroy() {
        if (this.sizeCheckInterval !== null) {
            clearInterval(this.sizeCheckInterval);
        }
    }
}

子组件:

import {Component, Input, SimpleChange} from "@angular/core";
import { IParentProps } from "./ParentComponent";

@Component({
    directives: [],
    selector: "the-child",
    template: `child`
})
export class ChildComponent {
    @Input() parentProps: IParentProps;
    constructor() {
        this.parentProps = {
            width: 0,
            height: 0
        }
    }
    ngOnChanges(changes: { [propName: string]: SimpleChange }) {
        this.parentProps = changes["parentProps"].currentValue;
        console.log("parent dims changed");
    }

}

【讨论】:

  • 惊人的答案。感谢您抽出时间来写这个。它就像一个魅力。
  • @cjr 很高兴我能帮上忙
  • @AlexLockwood 是的,它有点老套;如果我现在这样做,我会使用 observable
  • 这个答案很好。还有我想出的那个。但似乎使用 ElementRef 不再是最佳实践了。
猜你喜欢
  • 1970-01-01
  • 2017-11-27
  • 1970-01-01
  • 2012-06-02
  • 1970-01-01
  • 2012-03-24
  • 1970-01-01
  • 1970-01-01
  • 2018-09-06
相关资源
最近更新 更多