Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the offsetHeight of an element in a parent component from the children?

Tags:

angular

I need to get the offsetHeight of the content <div> defined in the parent component (base layout) from my child component, so I can make another <div> with the same size.

I tried like this but got Cannot read property 'nativeElement' of undefined.

Here's the layout component:

  <!-- Main content -->
  <div class="main" #mainContentArea>

    <!-- Breadcrumb -->
    <ol class="breadcrumb">
      <app-breadcrumbs></app-breadcrumbs>
    </ol>

    <div class="container-fluid">
      <router-outlet></router-outlet>
    </div><!-- /.conainer-fluid -->
  </div>

And the child component typescript:

import { Component, OnInit, ElementRef, ViewChild, AfterViewInit } from '@angular/core';
import { Router } from '@angular/router';

export class PmsSyncComponent implements OnInit, AfterViewInit {

  constructor(
    private router: Router,
    private elRef:ElementRef
  ) { }

  @ViewChild('mainContentArea') elementView: ElementRef;
  ngOnInit() {
  }

  ngAfterViewInit() {
    alert(this.elementView.nativeElement.offsetHeighta);
  }

}

Is this possible? I need to make this container the same size of the content area to implement the drag and drop feature for file upload.

like image 425
Juliano Nunes Silva Oliveira Avatar asked Nov 27 '25 23:11

Juliano Nunes Silva Oliveira


2 Answers

As i said in the commments, you could easily do this with CSS, but you said you want to get access to the parent element:

You can do this by accessing the parentNode of the nativeElement of your ChildComponent like this (simplified):

constructor(private elRef:ElementRef) { 
}

ngAfterViewInit() {
    console.log(this.elRef.nativeElement.parentNode.offsetHeight);
}

Make sure you use it in your ngAfterViewInit. It would still work in ngOnInit but if your parent Component would have other child components as well, it probably will cause problems, because they don't initialize at the same time and your height could differ.

Hope it helps.

like image 135
malifa Avatar answered Nov 29 '25 15:11

malifa


To get parent you would need to use your attribute that you declared in your constructor like this:

this.elRef.nativeElement.parentElement.offsetHeight;
like image 41
Ramon Marques Avatar answered Nov 29 '25 17:11

Ramon Marques



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!