gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:00:00 24 4
gpt4 key购买 nike

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

目前我能看到的唯一可能性是进行某种轮询,我们在子组件内部检查其宽度是否每隔 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");
}

}

关于resize - Angular2 Component 在 parent 的调整大小发生变化时监听,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37080343/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com