如何从 Angular 中弹性框中的组件获取元素信息



我有一个组件,其中包含一个子组件的弹性框。 我正在尝试从父组件中获取每个组件的元素宽度等信息。 我最后要做的是知道列表是否溢出,以便我可以修改可见元素的数量。 如果它溢出了,我想在末尾放置一个特殊元素,显示当前隐藏的图标数量。

我尝试使用@ViewChildren但无法弄清楚如何从中获取元素尺寸。 我该怎么做呢?

<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; */
}

沙盒:

https://codesandbox.io/s/j733w4w7ww

您可以为父级和子级依赖 Element.getBoundingClientRect(),如果子项的.bottom大于父项(双关语),则可以在子项上设置私有属性。

根据此属性,您可以隐藏溢出的并在父级中计算它们。

https://codesandbox.io/s/q8o798v2kw

相关代码(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;
}

最新更新