2

I have a plunker here - https://plnkr.co/edit/fzNJ7FLYxWbLPoxtYpEw?p=preview

Its a simple angular app.

I'm capturing the height of a div using @ViewChild and nativeElement.offsetHeight

Is it possible to uss this number in the styles block of the component.

In my example I have attempted it but commmented it out.

@Component({
  selector: 'my-app',
  templateUrl: './src/app.html',
  styles: [`
    .blockTwo {
      background: yellow;
      //height: this.contentHeight+px;
      height: 200px;
    }
  `]
})

=

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

@Component({
  selector: 'my-app',
  templateUrl: './src/app.html',
  styles: [`
    .blockTwo {
      background: yellow;
      //height: this.contentHeight+px;
      height: 200px;
    }
  `]
})

export class AppComponent implements AfterViewInit{

  @ViewChild('content') 
  elementView: ElementRef;

  contentHeight: number;

  constructor() {

  }

  ngAfterViewInit() {
      this.contentHeight = this.elementView.nativeElement.offsetHeight;
  }

}
1
  • You can use this style binding syntax: [style.height.px]="contentHeight". Commented Apr 24, 2018 at 13:57

3 Answers 3

2

This is doable using ngStyle

In your app.html change the yellow div to this:

<div class="blockTwo" [ngStyle]="style">
</div>

and in your app.ts

style: any;
ngAfterViewInit() {
  this.contentHeight = this.elementView.nativeElement.offsetHeight;
  this.style = {"height": this.contentHeight+"px"}
}
Sign up to request clarification or add additional context in comments.

Comments

1

User [ngStyle] Directive.

<div class="content" #content [ngStyle]="{'height':'contentHeight'}">

</div>

<div>
  <h2>{{contentHeight}}</h2>

  <div class="blockTwo">

  </div>
</div>

2 Comments

This doesn't seem to work for me - I need the '.blockTwo' to use the height - plnkr.co/edit/fzNJ7FLYxWbLPoxtYpEw?p=preview
In your plnkr style is not defined. Use this code below elementView to define. elementView: ElementRef; style:{"height": string};
1

you can just do like this

//this line is exaple , but point is make use of ngStyle
<some-element [ngStyle]="{'max-height.px': height}">...</some-element>

and define and initialize height in your ts file , that will do work for you

or kind of this help

<div #parentdiv style="background-color:blue;height:1000px">
  <div [ngStyle]="{'max-height.px': parentdiv.offsetHeight}">
    hallo
  </div>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.