Rolando
Rolando

Reputation: 62664

How to in angular2 detect if the contents of a div trigger an overflow:auto?

I have in my HTML template with a div box I want to detect when the scrollbar appears/when overflow:auto is triggered because the size of the box is smaller than the content inside of it. I want to make it so that if the content of the parentDiv is bigger than the overflow... then show the message:

<div>
    <div id="parentDiv" style="overflow:auto;height:400px;width:100px;">
    <span *ngIf="<function that checks if the content of this the parent div #parentDiv>">Content Too Big!</span>
    Text Text Text
    </div>
</div>

Is there some easy way to do this in angular2/4? Assume the entire template is for one component.

Upvotes: 1

Views: 1377

Answers (1)

ralzohairi
ralzohairi

Reputation: 74

The approach I'm suggesting is basically using the condition "is the height of the child div greater than the height of the parent div".

Using that condition to trigger both a message and an "overflow: auto" property. So, the overflow property will be added after the condition is met.

You can always change the condition to adjust the ratio, so maybe if the child is 3/4 the height of the parent div.

Also, you can change when the condition is checked, maybe remove it from ngOnInit to another function that gets triggered upon an event.

Note that I used Local reference and Element ref to access the element's style in the typescript file.

Template: app.component.html

<!-- visible is the default overflow view -->
<div 
class="parent"
style="background-color: red; height: 200px; width: 200px"
[ngStyle]="{overflow: childOverflow? 'auto': 'visible'}"
#parent>
  <div
  class="child"
  style="background-color: pink; margin: 5px"
  #child>
    Lorem ipsum dolor sit amet, an veritus habemus sea. At eum oportere hendrerit constituam, alii ubique fabulas in est. An stet salutandi pro. At eos graeci consetetur. Nec ne quis dignissim, mea ei feugait maluisset, ne fastidii rationibus vis. Sit erat homero cu, sale liber perpetua cum ex, electram consequuntur est te.
  </div>
</div>

Typescript file: app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {


  childOverflow = false;

  @ViewChild('parent') parent: ElementRef;
  @ViewChild('child') child: ElementRef;

  ngOnInit(){

    //client height gets you the exact height if its in percentage or not set yet
    let parentHeight = parseInt(this.parent.nativeElement.clientHeight);
    let childHeight = parseInt(this.child.nativeElement.clientHeight);

    if (childHeight >= parentHeight){
        this.childOverflow = true;
        alert("Content Too Big!");
    }
  }
}

Upvotes: 2

Related Questions