Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/428.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript @ViewChildren中QueryList的顺序是否始终与DOM中的顺序匹配?_Javascript_Angular - Fatal编程技术网

Javascript @ViewChildren中QueryList的顺序是否始终与DOM中的顺序匹配?

Javascript @ViewChildren中QueryList的顺序是否始终与DOM中的顺序匹配?,javascript,angular,Javascript,Angular,假设我有几个my components,我想查询它们的列表: <li><my-component>#1</my-component><li> <li><my-component>#2</my-component><li> <li><my-component>#3</my-component><li> 这里我唯一关心的是,我不确定顺序是否总是与DOM中的

假设我有几个
my component
s,我想查询它们的列表:

<li><my-component>#1</my-component><li>
<li><my-component>#2</my-component><li>
<li><my-component>#3</my-component><li>
这里我唯一关心的是,我不确定顺序是否总是与DOM中的顺序相同。没有提到任何关于订购的事情。在我的例子中,顺序很重要,因为我试图选择具有给定索引的组件


@ViewChildren
设置的查询列表的顺序是否总是与DOM中的顺序匹配?

它并不总是与DOM顺序匹配

如果在运行时移动或添加项,则QueryList的顺序将关闭。这发生在我的@angular/material表中,带有拖放

要解决这个问题,必须在传递已排序子项的QueryList上调用reset。这是通过订阅QueryList更改来实现此目的的一种方法:

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));
const rowChange$:Observable=this.rows.changes;
常量indexOfRow=(行:MatRow)=>{
返回[…this.\u elementRef.nativeElement.children].indexOf(row.elementRef.nativeElement);
};
const sortedRows$=行更改$.pipe(
映射(rows=>rows.toArray()),
过滤器(行=>rows.length>1),
map(rows=>rows.sort((a,b)=>indexOfRow(a)-indexOfRow(b)))
);
分拣机$
.pipe(takeUntil(this.sub))
.subscribe(sortedRows=>this.rows.reset(sortedRows));

是的,它们与DOM的顺序相匹配。但如果需要,您可以重新排序。只需转换为数组,对数组排序并使用reset
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));