【问题标题】:Angular 4 event after element displayed with *ngIf使用 *ngIf 显示的元素后的 Angular 4 事件
【发布时间】:2018-05-04 06:02:49
【问题描述】:

我有一个演示 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);
  }
}

【问题讨论】:

标签: angular


【解决方案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

【讨论】:

    【解决方案2】:

    你可以使用 hidden 代替 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: 块。

    【讨论】:

      【解决方案3】:

      我也遇到过类似的情况,我的 Angular 组件在 ngIf 条件之后被渲染,我想使用元素的高度来获得一些类。 正如约翰上面所说的“你所要做的就是在你显示你的 html 元素时等待 Angular 运行它的更改检测”。但是在他的回答中有时会出现一个问题,我们可能不知道运行更改检测所需的时间,所以在我的情况下打勾后不起作用。 由于无法捕获 *ngIf 事件,所以我作为 hack 所做的就是在函数内部再次调用该函数,如果元素的高度为 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);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-25
        • 1970-01-01
        • 2021-03-07
        • 2017-05-11
        • 2018-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多