2017-03-10 36 views
0

我有一个ngFor循环,像这样:Angular2 * ngFor循环越来越高(只得到第一个)

hf() { 
    this.heighty = document.getElementById('juliet').offsetHeight; 
    console.log("juliet function height = " + this.heighty); 

    } 

但是:<div *ngFor="let group of catt" id="juliet" [ngClass]="hf()">这里我所说的HF(),每个看起来像这样时间功能for循环经历了4次数据处理,但仅给出了第一个循环的高度,然后为每个循环提供了相同的高度。当我检查元素时,我会看到具有不同高度的4个环。我也没有看到每个循环的标识符,如juliet[0]。我如何获得for循环的每个循环的高度?

回答

2

请勿使用id,因为它将在页面上多次重复该DOM(尽管document.getElementById('juliet')将为元素的第一个实例),而不是像下面显示的使用模板变量#juliet

<div *ngFor="let group of catt" #juliet [ngClass]="hf(juliet)"> 

然后通过在hf方法传递juliet计算每个DOM的高度。

hf(element) { 
    this.heighty = element.offsetHeight; 
    console.log("juliet function height = " + this.heighty); 
} 
+1

非常感谢CLEAR答案,它的效果非常好! –