Angular2 Component 在 parent 的调整大小发生变化时监听

Angular2 Component listen when parent's resize change

我有一个要求,我想通过方法调用根据其 parent 组件的大小更改 child 组件的属性。我 运行 遇到的问题是,我能听到的唯一调整大小事件是 window 的事件,这没有帮助,因为 window 大小没有改变,只有 parent 组件是由于侧面板 div 打开和关闭。

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

感谢您的帮助!

你是正确的,你无法在 div 上获得调整大小事件(没有安装一些 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");
    }

}