1

I have a component with a flex box of child components. I'm trying to get information like the element width of each component from with in my parent component. What I'm trying to do in the end is know if the list is overflowed so I can modify the number of visible elements. If it is overflowed, I'd like to put a special element at the end that shows the number of icons that are currently hidden.

I've tried using the @ViewChildren but can't figure out how to get the element dimensions from this. How can I go about doing this?

<div class="file-list">
    <app-file-icon [text]="file" *ngFor="let file of files"></app-file-icon>
</div>

css:

.file-list {
  width: 200px;
  height: 120px;
  border: 1px solid grey;
  padding: 10px;
  margin: 10px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  /* overflow: hidden; */
}

sandbox:

https://codesandbox.io/s/j733w4w7ww

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
ErpaDerp
  • 780
  • 1
  • 7
  • 16
  • You won't be able to show the number of hidden items without Javascript. What's the desired functionality for the rest of the list? Hidden permanently or do you want like a [see more](https://stackoverflow.com/questions/12307666/how-to-create-a-show-more-button-and-specify-how-many-lines-of-text-can-be-ini) button? – sallf Dec 24 '18 at 04:08
  • @sallf Yes, something along the lines of a show more, but I'm not sure what the exact behavior will be at this time. I think it is independent of the first thing I'm trying to do which is limit the number of visible elements and add the +n icon to the list. I updated the sample to roughly demo what I'm going for. – ErpaDerp Dec 24 '18 at 04:16
  • Can you post more of your code here? How is the list being generated? One way would be to get the `bottom` position of the wrapping `div` and then counting the items in your list that have a `top` position greater than that. – sallf Dec 24 '18 at 05:10

1 Answers1

3

You can rely on Element.getBoundingClientRect() for both parent and child and set a private property on children if their .bottom is bigger than the parent's (pun intended).

Based on this property you can then hide the overflowing ones and count them in the parent.

https://codesandbox.io/s/q8o798v2kw

Relevant code (in file-icon.component.ts):

ngAfterViewInit() {
  let fileIcon = this.elemRef.nativeElement.querySelector(".file-icon"),
      b1 = fileIcon.getBoundingClientRect(),
      fileList = fileIcon.closest(".file-list"),
      b2 = fileList.getBoundingClientRect();
  this.hidden = b2.bottom < b1.bottom;
}
tao
  • 82,996
  • 16
  • 114
  • 150