我有一个要求,我想通过方法调用,根据其父组件的大小更改子组件的属性.我遇到的问题是我可以听到的唯一调整大小事件是窗口的调整事件,因为窗口大小没有变化,所以没有帮助,只有父组件是由于侧面板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");
}
}