简体   繁体   English

来自@ViewChildren 的 QueryList 的排序是否总是与 DOM 中的排序相匹配?

[英]Does the ordering of the QueryList from @ViewChildren always match with the ordering in the DOM?

Suppose I have a few my-component s and I would like to query a list of them:假设我有几个my-component并且我想查询它们的列表:

<li><my-component>#1</my-component><li>
<li><my-component>#2</my-component><li>
<li><my-component>#3</my-component><li>

Using @ViewChildren I can get a list (for example through .toArray ) that might look like the following:使用@ViewChildren我可以获得一个列表(例如通过.toArray ),它可能如下所示:

[
    /* reference to #1 component*/,
    /* reference to #2 component*/,
    /* reference to #3 component*/
]

My only concern here is that I am not sure whether the order will always be the same as it is in the DOM.我唯一担心的是,我不确定顺序是否总是与 DOM 中的顺序相同。 The documentation does not mention anything regarding the ordering.该文档没有提及有关订购的任何内容。 The order matters in my case because I am trying to select the component with a given index.顺序对我来说很重要,因为我试图选择具有给定索引的组件。

Does the ordering of the QueryList set by @ViewChildren always match with the ordering in the DOM? @ViewChildren 设置的@ViewChildren的顺序是否始终与 DOM 中的顺序匹配?

It does not always match the DOM-order.它并不总是与 DOM 顺序匹配。

If items are moved or added run time, the order of the QueryList will be off.如果项目被移动或添加运行时,QueryList 的顺序将关闭。 This happened to me in an @angular/material table with drag-drop.这发生在带有拖放功能的@angular/material 表中。

To solve it, you have to call reset on the QueryList passing sorted child items.要解决它,您必须在传递排序的子项的 QueryList 上调用 reset。 This is one way you could to that by subscribing to QueryList-changes:这是您可以通过订阅 QueryList-changes 来实现的一种方式:

const rowChange$: Observable<QueryList<MatRow>> = this.rows.changes;

const indexOfRow = (row: MatRow) => {
  return [...this._elementRef.nativeElement.children].indexOf(row.elementRef.nativeElement);
};

const sortedRows$ = rowChange$.pipe(
  map(rows => rows.toArray()),
  filter(rows => rows.length > 1),
  map(rows => rows.sort((a, b) => indexOfRow(a) - indexOfRow(b)))
);

sortedRows$
  .pipe(takeUntil(this.destroySub))
  .subscribe(sortedRows => this.rows.reset(sortedRows));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM