如何在angular2中检测div的内容是否触发溢出:auto?

时间:2018-03-23 15:47:47

标签: angular

我的HTML模板中有一个div框,我想检测滚动条何时出现/溢出时:auto是因为框的大小小于其内部的内容而触发的。我想这样做,如果parentDiv的内容大于溢出...然后显示消息:

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

在angular2 / 4中有一些简单的方法吗?假设整个模板用于一个组件。

1 个答案:

答案 0 :(得分:1)

我建议的方法基本上是使用条件“是子div的高度大于父div的高度”。

使用该条件触发消息和“overflow:auto”属性。因此,在满足条件后将添加overflow属性。

您可以随时更改条件以调整比例,因此,如果孩子的父级div的高度为3/4,则可能。

此外,您可以在检查条件时进行更改,也可以将其从ngOnInit中删除到另一个在事件中触发的函数。

请注意,我使用本地引用元素引用来访问typescript文件中的元素样式。

模板: 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>

打字稿文件: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!");
    }
  }
}