ttmt
ttmt

Reputation: 4984

Angular 4 get height of element on components parent

I have a demo here

I have a super simple parent component with a child component.

How can I get the height of the parent div from the child component.

import { Component, Input, ElementRef, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'child-comp',
  templateUrl: './child.component.html'
})

export class ChildComponent implements OnInit {

  @Input() parent: ElementRef;

  @ViewChild("self")
  self: ElementRef;

  constructor(){

  }

  ngOnInit(){
    //console.log(this.parent.nativeElement.clientHeight);
    console.log(this.self.nativeElement.offsetTop);
  }

}

Upvotes: 3

Views: 16533

Answers (2)

Tom Ford
Tom Ford

Reputation: 175

This seems to works well for me in ng17.

My specific scenario was that navigation content was dependent on async data and I wanted to set the top css rule for a floating navigation without hardcoding it.

I was running into all issues trying to set the value to a property because of the "Expression Changed After It was Checked" error, or the #content not being available yet in my observables or lifecycle methods.

@Component({
    selector: "navbar",
    template: `
        <nav #content>
            <ul [ngStyle]="{ 'top.px': navElement?.nativeElement?.offsetHeight || 0 }">
                ...
            </ul>  
        </nav>
    `,
})
export class AccountNavbarComponent {
    @ViewChild("content") public navElement?: ElementRef;
}

Upvotes: 0

diopside
diopside

Reputation: 3062

You need to use the 'AfterViewInit' lifecycle hook bc the view isn't fully initialized in NgOnInit and heights won't be calculated yet.

ngAfterViewInit() {
    let parentHeight = this.self.nativeElement.offsetParent.clientHeight;
}

A better way might be to write a directive that you can place on the parent that outputs the width with an event emitter, and then send that width to the child as an input. I don't always have great luck reading calculated properties off of a 'offsetParent' on a nativeElement.

Edit - using the parent as input

@Input() parent : HTMLElement;

ngAfterViewInit() {
     console.log(this.parent.clientHeight);
}

Upvotes: 6

Related Questions