Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Component listen when parent's resize change

Tags:

angular

resize

I have a requirement in which I want to change properties of a child component depending on the size of its parent component though a method call. The issue I am running into is that the only resize event I can listen to is that of the window, which doesn't help as the window size is not changing, only the parent component is due to a side panel div opening and closing.

The only possibility I can see at the moment is to have some sort of polling in which we within the child component itself that checks if its width has changed every x amount of time.

Thanks for your help!

like image 298
cjr Avatar asked Nov 09 '22 15:11

cjr


1 Answers

You are correct that you can't get the resize event on a div (without installing some js extension). But something like this works.

The Parent Component:

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);
        }
    }
}

The Child Component:

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");
    }

}
like image 152
brando Avatar answered Nov 15 '22 12:11

brando