加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

当父级调整大小更改时,Angular2组件侦听

发布时间:2020-12-17 16:55:31 所属栏目:安全 来源:网络整理
导读:我有一个要求,我想通过方法调用,根据其父组件的大小更改子组件的属性.我遇到的问题是我可以听到的唯一调整大小事件是窗口的调整事件,因为窗口大小没有变化,所以没有帮助,只有父组件是由于侧面板div打开和关闭. 我目前唯一可以看到的可能是进行某种轮询,其中
我有一个要求,我想通过方法调用,根据其父组件的大小更改子组件的属性.我遇到的问题是我可以听到的唯一调整大小事件是窗口的调整事件,因为窗口大小没有变化,所以没有帮助,只有父组件是由于侧面板div打开和关闭.

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

谢谢你的帮助!

解决方法

你是不对的,你不能在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");
    }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读