问题
I have a div element that is looped through an array of objects using *ngFor. The height of a particular div is different from each other as each object contains different amounts of word count. I want to get the largest div element's height and set it as the div height so all div elements look the same. I am using Bootstrap 4.xx
<div class="col-md-4" *ngFor="let food of foods">
<div class="food-card">
<h4>{{food.title}}</h4>
<p>{{food.ingredients}}</p>
</div>
</div>
Ingredients contain a lot of words in it and the word count varies from each food item.
回答1:
You can use ViewChildren to get the elements, and in ngAfterViewInit, get the size
<div class="col-md-4" *ngFor="let food of foods">
<div #foodcard class="food-card">
<h4>{{food.title}}</h4>
<p>{{food.ingredients}}</p>
</div>
</div>
@ViewChildren('foodcard') foodCards:QueryList<ElementRef>
ngAfterViewInit()
{
let maxHeight=0
this.foodCards.forEach(x=>{
const height=x.nativeElement.getBoundingClientRect().height
if (heigth>maxHeight)
maxHeight=height
})
}
Anyway, if your aim is set the same height check card-deck
来源:https://stackoverflow.com/questions/62227026/finding-height-of-the-largest-div-element-and-setting-it-for-all-div-elements-an