Reputation: 8177
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.
Upvotes: 3
Views: 10385
Reputation: 8165
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.
Upvotes: 4
Reputation: 3264
To get parent you would need to use your attribute that you declared in your constructor like this:
this.elRef.nativeElement.parentElement.offsetHeight;
Upvotes: 1