元素与* ngIf

时间:2018-05-04 06:02:49

标签: angular

我有一个演示Here

我在组件中有一个div,显示为* ngIf

我需要知道这个元素的高度。

我似乎无法在显示之前或在显示元素的函数中执行此操作。

是否有可以用来获取高度的事件

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

@Component({
  selector: 'child-comp',
  templateUrl: './child.component.html'
})

export class ChildComponent implements OnInit, AfterViewInit {

  @Input() parent: ElementRef;

  private block: ElementRef;

  @ViewChild('block') set content(content: ElementRef) {
    this.block = content;
 }

  show: boolean = false
  blockHeight: number

  constructor(){ }

  // ngOnInit(){
  //   this.blockHeight = this.block.nativeElement.clientHeight;
  // }

  ngAfterViewInit(){
    this.blockHeight = this.block.nativeElement.clientHeight;
    console.log('AfterViewInit '+this.blockHeight);
  }

  showBlock(){
    this.show = !this.show
    this.blockHeight = this.block.nativeElement.clientHeight;
    console.log('showBlock '+this.blockHeight);
  }
}

3 个答案:

答案 0 :(得分:1)

您需要做的是等待Angular在您显示html元素时运行其更改检测。在setTimeout() - 方法中放入showBlock(),等待勾选,然后定义块元素(它存在于DOM中)。在显示元素之前,您无法获得元素的高度,因为它不存在于DOM中。

在你的showBlock方法中:

showBlock(){
    this.show = !this.show
    setTimeout(()=>{ // wait a tick in order to get the element of block
     this.blockHeight = this.block.nativeElement.clientHeight;
     console.log('showBlock '+this.blockHeight);
    });
  }

查看更新的Stackblitz

答案 1 :(得分:0)

您可以使用隐藏而不是ngIf: -

<div>
  <button (click)="showBlock()">Show Block</button>
</div>
<div class="child-component" [hidden]="show" #block>
  <a href="">Link</a>
  <a href="">Link</a>
  <a href="">Link</a>
  <a href="">Link</a>
</div>

并使用从.child-component类中删除display:block。

答案 2 :(得分:0)

我也遇到过类似的情况,在ngIf条件之后渲染了我的Angular组件,我想使用元素的高度来获取一些类。 就像约翰在上面说的那样:“您需要做的就是在显示html元素时等待Angular运行其更改检测”。但是在他的回答中有时会出现问题,我们可能不知道运行更改检测所花费的时间,因此在我的情况下,打勾不起作用。 由于无法捕获* ngIf事件,因此作为黑客,我再次在函数内部调用该函数,如果元素的高度为0,则需要该元素的高度。请参见

showBlock(){
  let self = this;
  this.show = !this.show
  if(this.show && this.block.nativeElement.clientHeight == 0){
    setTimeout(() => { 
               self.showBlock();
     },500); // After a tick execute again
    return;
   }//End If

this.blockHeight = this.block.nativeElement.clientHeight;
console.log('showBlock '+this.blockHeight);
}
相关问题