2
votes

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

}
3
You can use this style binding syntax: [style.height.px]="contentHeight".ConnorsFan

3 Answers

2
votes

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"}
}
1
votes

User [ngStyle] Directive.

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

</div>

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

  <div class="blockTwo">

  </div>
</div>
1
votes

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>